简体   繁体   中英

Parse date time with PM/AM

I want to parse the following date-time format:

8/1/2013 3:52:05 PM

What should I use for format ?

DateTime.ParseExact("8/1/2013 3:52:05 PM", "format", CultureInfo.InvariantCulture);

Custom Date and Time Format Strings

"tt" - The AM/PM designator.

So your format string should be: M/d/yyyy h:mm:ss tt

Console.WriteLine(DateTime.ParseExact("8/1/2013 3:52:05 PM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture));

prints 2013-08-01 15:52:05

But, you can easily do the same without specifying the format:

DateTime.Parse("8/1/2013 3:52:05 PM", CultureInfo.GetCultureInfo("en-us"))

Works just fine. Your input is formatted using en-US format.

DateTime date = DateTime.ParseExact("8/1/2013 3:52:05 PM", "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine(date);

Output will be;

1/8/2013 3:52:05 PM

Here a DEMO .

Further reading;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM