2013-04-09 256 views
12

我遇到了問題。我正在從數據庫獲取日期時間字符串,並且這些日期時間字符串中的一些不包含時間。但作爲新的要求每一個日期時間字符串應該包含的時間,像這樣,檢查日期時間字符串是否包含時間

1)1980/10/11 12:00:01 2)2010/APRIL/02 17:10:00 3)10/02/10 03:30:34

日期可以是任何格式,然後在24hr符號的時間。

我試圖通過下面的代碼來檢測時間的存在,

string timestamp_string = "2013/04/08 17:30"; 
DateTime timestamp = Convert.ToDateTime(timestamp_string); 
string time =""; 

if (timestamp_string.Length > 10) 
{ 
    time = timestamp.ToString("hh:mm"); 
} 
else { 
    time = "Time not registered"; 
} 

MessageBox.Show(time); 

但對於沒有1)型時間戳這僅適用。請讓我知道如何實現這個任務,瞭解如何檢測日期時間字符串中是否存在時間元素。非常感謝你:)

可能匹配 How to validate if a "date and time" string only has a time?

信息通過Arun Selva KumarGuru KaraPatipol Paripoonnanonda提供的三個答案是正確的,並檢查的時間和我的服務宗旨。但我選擇Guru Kara的答案完全取決於易用性和他給出的解釋。非常感謝你:)非常感謝大家:)

回答

12

日期時間部件TimeOfDay是你需要什麼。

MSDN says 「與Date屬性不同,Date屬性返回DateTime值,該值表示沒有時間分量的日期,TimeOfDay屬性返回表示DateTime值時間分量的TimeSpan值。」

以下是考慮所有場景的示例。
既然你是肯定的格式,你可以用別的DateTime.Parse請使用DateTime.TryParse

var dateTime1 = System.DateTime.Parse("1980/10/11 12:00:00"); 
var dateTime2 = System.DateTime.Parse("2010/APRIL/02 17:10:00"); 
var dateTime3 = System.DateTime.Parse("10/02/10 03:30:34"); 
var dateTime4 = System.DateTime.Parse("02/20/10"); 

if (dateTime1.TimeOfDay.TotalSeconds == 0) { 
    Console.WriteLine("1980/10/11 12:00:00 - does not have Time"); 
} else { 
    Console.WriteLine("1980/10/11 12:00:00 - has Time"); 
} 

if (dateTime2.TimeOfDay.TotalSeconds == 0) { 
    Console.WriteLine("2010/APRIL/02 17:10:00 - does not have Time"); 
} else { 
    Console.WriteLine("2010/APRIL/02 17:10:00 - Has Time"); 
} 

if (dateTime3.TimeOfDay.TotalSeconds == 0) { 
    Console.WriteLine("10/02/10 03:30:34 - does not have Time"); 
} else { 
    Console.WriteLine("10/02/10 03:30:34 - Has Time"); 
} 

if (dateTime4.TimeOfDay.TotalSeconds == 0) { 
    Console.WriteLine("02/20/10 - does not have Time"); 
} else { 
    Console.WriteLine("02/20/10 - Has Time"); 
} 
+0

嘿謝謝你的回覆:)我會通過n回發:) – 2013-04-09 05:28:30

+2

-1:此方法失敗的任何日期時間字符串與指定的午夜時間;例如對於「2015-02-26T00:00」我期望得到「有時間」,但是System.DateTime.Parse(「2015-02-26T00:00」)。TimeOfDay.TotalSeconds的計算結果爲0.0。 – 2015-02-26 10:22:34

+0

在第一句中,該方法的名稱拼寫錯誤。我試圖編輯它,但stackoverflow用戶界面說,編輯必須至少有六個字符。另外,我同意Kasper van den Berg所說的答案不符合要求。 – 2015-11-04 17:08:15

9

試試這個,

DateTime myDate; 
if (DateTime.TryParseExact(inputString, "dd-MM-yyyy hh:mm:ss", 
    CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate)) 
{ 
    //String has Date and Time 
} 
else 
{ 
    //String has only Date Portion  
} 

您可以嘗試使用其他格式說明如下所列,http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

+0

嘿thanx的答覆:)我會嘗試這n個後回來:) – 2013-04-09 04:52:30

+0

如果字符串不是約會,否則你將給出錯誤的答案。您需要使用另一個DateTime.TryParseExact作爲日期格式。 – Akanksha 2013-04-09 05:06:20

+0

嘿我試過這個,但它總是給出錯誤信息?你知道嗎? 'string a =「08/04/2013 17:34:00」; DateTime myDate; (DateTime.TryParseExact(a,「dd/MM/yyyy hh:mm:ss」, CultureInfo.InvariantCulture,DateTimeStyles.None,out myDate)) { MessageBox.Show(「Correct」); //字符串有日期和時間 } else { MessageBox.Show(「Error」); //字符串只有日期部分 }' – 2013-04-09 05:09:56

-1

的日期和時間總是用空格分開吧。最簡單的方法是:

if (timestamp_string.Split(' ').Length == 2) 
{ 
    // timestamp_string has both date and time 
} 
else 
{ 
    // timestamp_string only has the date 
} 

此代碼假定日期總是存在。

如果你想採取進一步(以防日期不存在),你可以這樣做:

if (timestamp_string.Split(' ') 
        .Select(item => item.Split(':').Length > 1) 
        .Any(item => item)) 
{ 
    // this would work for any string format that contains date, for example: 
    // 2012/APRIL/03 12:00:05 -> this would work 
    // 2013/04/05 09:00:01 -> this would work 
    // 08:50:45 2013/01/01 -> this would also work 
    // 08:50:50 -> this would also work 
} 
else 
{ 
    // no date in the timestamp_string at all 
} 

希望這有助於!

+0

嗨thanx回覆我會檢查這個併發回:) – 2013-04-09 05:28:13

+0

你有機會嘗試它嗎?請告訴我。 – Pat 2013-04-10 05:04:05

+0

hey..hi..sorry爲延遲..我選擇了一個答案,我解釋了爲什麼在問題本身..非常感謝幫助:)非常感謝。 – 2013-04-11 10:19:44

2

結合Guru KaraPatipol Paripoonnanonda的答案與。在淨全球化API的結果:

bool HasExplicitTime(DateTime parsedTimestamp, string str_timestamp) 
{ 
    string[] dateTimeSeparators = { "T", " ", "@" }; 
    string[] timeSeparators = { 
     CultureInfo.CurrentUICulture.DateTimeFormat.TimeSeparator, 
     CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator, 
     ":"}; 

    if (parsedTimestamp.TimeOfDay.TotalSeconds != 0) 
     return true; 

    string[] dateOrTimeParts = str_timestamp.Split(
      dateTimeSeparators, 
      StringSplitOptions.RemoveEmptyEntries); 
    bool hasTimePart = dateOrTimeParts.Any(part => 
      part.Split(
        timeSeparators, 
        StringSplitOptions.RemoveEmptyEntries).Length > 1); 
    return hasTimePart; 
} 

這種方法:

  • 檢測明確的午夜時間(例如 「2015-02-26T00:00」);
  • 只有當TimeOfDay表示午夜或沒有明確時間時才搜索字符串;和
  • 發現本地格式的明確午夜時間和任何.net可以解析的格式的非午夜時間。

限制:

  • 在非文化本地格式明確的午夜時間不檢測;
  • 明確午夜時間少於兩部分未檢測到;和
  • 不如Guru Kara和Patipol Paripoonnanonda的方法簡單和優雅。
0

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