Why can’t DateTime.ParseExact() parse the AM/PM in

2019-01-07 19:29发布

I'm using c#, and if I do

DateTime.ParseExact("4/4/2010 4:20:00 PM", "M'/'d'/'yyyy H':'mm':'ss' 'tt", null)

The return value is always 4:20 AM -- what am I doing wrong with using tt?

Thanks!

3条回答
三岁会撩人
2楼-- · 2019-01-07 19:48

You need to use a lowercase "h" for the hour argument in the format string. The uppercase "H" represents 24-hour time, so "4" is recognized as 4 AM (since "16" would be 4 PM).

DateTime.ParseExact("4/4/2010 4:20:00 PM", "M/d/yyyy h:mm:ss:tt", null)
查看更多
再贱就再见
3楼-- · 2019-01-07 19:49

Try the following:

Console.WriteLine(DateTime.ParseExact("4/4/2010 4:20:00 PM", "M'/'d'/'yyyy h':'mm':'ss tt", null));

This outputs:

 4/4/2010 4:20:00 PM
查看更多
叛逆
4楼-- · 2019-01-07 19:56

Make the hour format (H) lowercase like this:

DateTime.ParseExact(
            "4/4/2010 4:20:00 PM", 
            "M/d/yyyy h:mm:ss tt", 
            CultureInfo.InvariantCulture);

Uppercase "H" indicates 24-hour time and lowercase "h" indicates 12-hour time and will respect the AM/PM in the candidate string.

Side note: It is best to provide an instance of IFormatProvider to methods like this (even if it's just CultureInfo.InvariantCulture). It's one of those things that doesn't really matter until you hit problems with it so it can be good to be in the habit of specifying culture information.

查看更多
登录 后发表回答