C# 在C中将日期和时间字符串转换为日期时间#
我有一个字符串,它以以下格式显示日期和时间: 2013年1月3日星期四15:04:29 我如何将其转换为日期时间?我试过:C# 在C中将日期和时间字符串转换为日期时间#,c#,datetime,converter,C#,Datetime,Converter,我有一个字符串,它以以下格式显示日期和时间: 2013年1月3日星期四15:04:29 我如何将其转换为日期时间?我试过: string strDateStarted = "Thu Jan 03 15:04:29 2013" DateTime datDateStarted = Convert.ToDateTime(strDateStarted); 但这是行不通的。在我的程序中,该值是从日志文件中读取的,因此我无法更改文本字符串的格式。尝试使用 在您的情况下,应: Thu Jan 03 15:0
string strDateStarted = "Thu Jan 03 15:04:29 2013"
DateTime datDateStarted = Convert.ToDateTime(strDateStarted);
但这是行不通的。在我的程序中,该值是从日志文件中读取的,因此我无法更改文本字符串的格式。尝试使用
在您的情况下,应:
Thu Jan 03 15:04:29 2013
电话应该是这样的:
DateTime logDate = DateTime.ParseExact(logValue, "ddd MMM dd HH:mm:ss yyyy",
CultureInfo.CreateSpecificCulture("en-US"));
第三个参数设置为美国文化,因此ddd
和MMM
部分分别对应于Thu
和Jan
在本例中,我建议使用
ParseExact
而不是TryParseExact
,因为数据的来源。如果要分析用户输入,请始终使用TryParseExact
,因为您不能相信用户遵循了请求的格式。但是,在这种情况下,源文件是一个具有良好定义格式的文件,因此任何无效数据都应视为异常,因为它们是异常的
还要注意的是,
*ParseExact
方法是非常不可原谅的。如果数据不完全符合指定的格式,则将其视为错误。查看使用*Parse*
上定义的方法之一
TryParseExact
或ParseExact
将采用与日期字符串对应的格式字符串
我建议仔细阅读
在这种情况下,相应的格式字符串为:
"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)
使用以下代码:
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小时格式,请使用HH 类似于DateTime.ParseExact(str,“ddd-MMM-dd-HH:mm:ss-yyyy”,null)
HH
是一种12小时格式谢谢您的回复!你的建议不太管用,但Arshad的建议是:DateTime.TryParseExact(strDateStarted,新字符串[]{“ddd-MMM-dd-HH:mm:ss-yyyy”},System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None,out-dateStarted)代码>起作用了。效果很好!
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);