简体   繁体   中英

The format string for DateTime.ParseExact - what hour format works with “tt”?

I want to convert string 5/4/2017 2:15:50 PM to a datetime. I used

statustime="5/4/2017 2:15:50 PM"
statustimefrm=DateTime.Parse(statustime, Globalization.CultureInfo.CurrentCulture)

and it worked, but I would rather use ParseExact. I used

statustimefrm=DateTime.Parse(statustime,  "M/d/yyyy HH:mm:ss tt",Globalization.CultureInfo.CurrentCulture)

but it gave me a format error. Would anybody know the format to use?

"HH" is not compatible with "tt" - you either have 24 hour time or 12 hours plus AM/PM designators. You need to use h for time :

 DateTime.ParseExact("5/4/2017 2:15:50 PM",  "M/d/yyyy hh:mm:ss tt",
       new CultureInfo("en-US")) 

这适合我

DateTime.ParseExact(timespan, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

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