C# 如何解析此日期时间字符串?

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

我搞不懂,我哪里出错了

我获得了以下datetime字符串,需要将其解析为datetime:

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