这就是我现在要做的。这可能并不完美,但可能比考虑任何上午12点的日期时间没有时间更好。前提是,如果我在最终解决全时间规范时会解析它是否仅仅是一个日期,但如果它已经有一个时间组件则会失败。
我不得不假设没有一些有效的日期/时间有7个非空白字符或更少。看起来“1980/10”是解析,但不是“1980/10 01:01:01.001”。
我已经包含了各种测试用例。随意添加你自己的,让我知道他们是否失败。
public static bool IsValidDateTime(this string dateString, bool requireTime = false)
{
DateTime outDate;
if(!DateTime.TryParse(dateString, out outDate)) return false;
if (!requireTime) return true;
else
{
return Regex.Replace(dateString, @"\s", "").Length > 7
&& !DateTime.TryParse(dateString + " 01:01:01.001", out outDate);
}
}
public void DateTest()
{
var withTimes = new[]{
"1980/10/11 01:01:01.001",
"02/01/1980 01:01:01.001",
"1980-01-01 01:01:01.001",
"1980/10/11 00:00",
"1980/10/11 1pm",
"1980-01-01 00:00:00"};
//Make sure our ones with time pass both tests
foreach(var date in withTimes){
Assert.IsTrue(date.IsValidDateTime(), String.Format("date: {0} isn't valid.", date));
Assert.IsTrue(date.IsValidDateTime(true), String.Format("date: {0} does have time.", date));
}
var withoutTimes = new[]{
"1980/10/11",
"1980/10",
"1980/10 ",
"10/1980",
"1980 01",
"1980/10/11 ",
"02/01/1980",
"1980-01-01"};
//Make sure our ones without time pass the first and fail the second
foreach (var date in withoutTimes)
{
Assert.IsTrue(date.IsValidDateTime(), String.Format("date: {0} isn't valid.", date));
Assert.IsFalse(date.IsValidDateTime(true), String.Format("date: {0} doesn't have time.", date));
}
var bogusTimes = new[]{
"1980",
"1980 01:01",
"80 01:01",
"1980T01",
"80T01:01",
"1980-01-01T01",
};
//Make sure our ones without time pass the first and fail the second
foreach (var date in bogusTimes)
{
DateTime parsedDate;
DateTime.TryParse(date, out parsedDate);
Assert.IsFalse(date.IsValidDateTime(), String.Format("date: {0} is valid. {1}", date, parsedDate));
Assert.IsFalse(date.IsValidDateTime(true), String.Format("date: {0} is valid. {1}", date, parsedDate));
}
}
嘿谢谢你的回复:)我会通过n回发:) – 2013-04-09 05:28:30
-1:此方法失败的任何日期时间字符串与指定的午夜时间;例如对于“2015-02-26T00:00”我期望得到“有时间”,但是System.DateTime.Parse(“2015-02-26T00:00”)。TimeOfDay.TotalSeconds的计算结果为0.0。 – 2015-02-26 10:22:34
在第一句中,该方法的名称拼写错误。我试图编辑它,但stackoverflow用户界面说,编辑必须至少有六个字符。另外,我同意Kasper van den Berg所说的答案不符合要求。 – 2015-11-04 17:08:15