這就是我現在要做的。這可能並不完美,但可能比考慮任何上午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