C# 如何解析此日期时间字符串?
我搞不懂,我哪里出错了 我获得了以下datetime字符串,需要将其解析为datetime:C# 如何解析此日期时间字符串?,c#,string,datetime,datetime-parsing,C#,String,Datetime,Datetime Parsing,我搞不懂,我哪里出错了 我获得了以下datetime字符串,需要将其解析为datetime: string timestr = "1/20/2014 12:05:16 AM" 我试着这样解析它: DateTime.ParseExact( timestr, "MM/dd/yyyy hh:mm:ss tt", null); 当尝试这样做时,它会返回 “字符串未被识别为有效的日期时间” 有什么提示吗?是针对01到1
string timestr = "1/20/2014 12:05:16 AM"
我试着这样解析它:
DateTime.ParseExact( timestr,
"MM/dd/yyyy hh:mm:ss tt",
null);
当尝试这样做时,它会返回
“字符串未被识别为有效的日期时间”
有什么提示吗?是针对01
到12
改用用于1
到12
string timestr = "1/20/2014 12:05:16 AM";
var date = DateTime.ParseExact(timestr,
"M/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
Console.WriteLine(date);
输出将是
1/20/2014 12:05:16 AM
这里有一个
有关更多信息,请参阅
01
到12
,用于00
到23
。如果您的工作时间为13
、14
或15
等<代码>hh格式将失败
由于在DateTime.ParseExact
方法中使用null
作为IFormatProvider
,这意味着默认情况下它使用CurrentCulture
。如果它不是/
,则您的方法会抛出FormatException
,即使您的字符串和格式完全匹配,因为它在自定义日期和时间格式中有特殊含义,如;替换我当前区域性或辅助区域性日期分隔符尝试此分隔符:
this.RequestDate = Convert.ToDateTime(this.DcmCreateDate).ToString("dd/MM/yyyy");
你试过了吗
DateTime returnedDate = new DateTime();
DateTime.TryParse(timestr, out returnedDate);
M
-月份,从1到12
“M”自定义格式说明符将月份表示为1到12之间的数字(对于有13个月的日历,则表示为1到13之间的数字)。一位数月份的格式不带前导零
DateTime.ParseExact( timestr,"M/dd/yyyy hh:mm:ss tt",CultureInfo.InvariantCulture);
请再试一次
string timestr = "1/20/2014 12:05:16 AM";
DateTime dt = new DateTime();
DateTime.TryParse(timestr, out dt);
请不要只是发布代码,请向用户解释代码的作用,以便他们可以从中学习,因为这是他们来StackOverflow的原因。顺便说一下,您不必初始化
out参数<代码>日期时间dt代码>就足够了。如果OP的CurrentCulture
不接受M/dd/yyyy hh:mm:ss tt
作为标准日期和时间模式,您的DateTime.TryParse
返回false
,您的dt
将是01/01/0001 00:00:00
。如果OP的CurrentCulture
不接受M/dd/yyyy hh:mm:ss tt
作为标准日期和时间模式,您的DateTime.TryParse
返回false
,您的returnedDate
将为01/01/0001 00:00:00
。