2013-03-22 92 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); 
相关问题