2013-03-22 114 views
3

我有一個顯示日期和時間如下格式的字符串:轉換日期和時間字符串的DateTime在C#

週四年1月3 15點04分29秒2013

我將如何將它轉換爲一個DateTime ?我曾嘗試過:

string strDateStarted = "Thu Jan 03 15:04:29 2013" 
DateTime datDateStarted = Convert.ToDateTime(strDateStarted); 

但這不起作用。在我的程序中,這個值是從日誌文件讀入的,所以我無法改變文本字符串的格式。

+0

類似於'DateTime.ParseExact(str,「ddd MMM dd HH:mm:ss yyyy」,null)' – 2013-03-22 12:55:28

+0

[C#Convert date to datetime](https://www.google.se/search?q = C%23 +轉換+日期+到+日期時間) – Default 2013-03-22 12:56:01

回答

3

使用下面的代碼:

string strDateStarted = "Thu Jan 03 15:04:29 2013";   
DateTime datDateStarted; 
DateTime.TryParseExact(strDateStarted, new string[] { "ddd MMM dd HH:mm:ss yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out datDateStarted); 
Console.WriteLine(datDateStarted); 

和肯定,如果時間是24 HRS格式,然後使用HH。 More details

+0

完美的工作! – TroggleDorf 2013-03-22 13:24:40

3

嘗試使用DateTime.ParseExact

你的情況format specified應該是:

Thu Jan 03 15:04:29 2013 

和調用應該是這樣的:

DateTime logDate = DateTime.ParseExact(logValue, "ddd MMM dd HH:mm:ss yyyy", 
            CultureInfo.CreateSpecificCulture("en-US")); 

第三個參數被設置爲美國的文化,使dddMMM零件,分別對應於ThuJan


在這種情況下,我建議ParseExact代替TryParseExact,因爲數據的來源。如果您解析用戶輸入,則始終使用TryParseExact,因爲您不能相信用戶遵循了所請求的格式。但是,在這種情況下,源代碼是格式明確的文件,因此任何無效數據都應視爲異常,因爲它們是非常特殊的。

另外請注意,*ParseExact方法是非常unforgiving。如果數據不完全符合指定的格式,則將其視爲錯誤。

+0

感謝您的回覆!你的工作不太好,但是Arshad的建議是:'DateTime.TryParseExact(strDateStarted,new string [] {「ddd MMM dd HH:mm:ss yyyy」},System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles 。沒有,出datatateStarted);'工作。 – TroggleDorf 2013-03-22 13:23:17

7

使用上DateTime定義的*Parse*方法之一。

TryParseExactParseExact其中將採用對應於日期字符串的格式字符串。

我建議你閱讀Custom Date and Time Format Strings

在這種情況下,對應的格式字符串是:

"ddd MMM dd HH:mm:ss yyyy" 

的情況下使用:

DateTime.ParseExact("Thu Jan 03 15:04:29 2013", 
        "ddd MMM dd HH:mm:ss yyyy", 
        CultureInfo.InvariantCulture) 
+0

'hh'是一個12小時的格式 – 2013-03-22 12:58:00

+0

@lazyberezovsky - 是的,謝謝。 – Oded 2013-03-22 12:58:28

0
string yourDateTimeRepresentation = "R"; //for example 
DateTime dt = DateTime.ParseExact(strDateStarted , yourDateTimeRepresentation , System.Globalization.CultureInfo.CurrentCulture); 
相關問題