简体   繁体   中英

Parsing string to DateTime format

I have following string "16:07:57.796" how i can parse it to this 6/18/2011 16:07:57 ?

If I just try to parse it DateTime.Parse("16:07:57.796") I get 6/18/2011 04:07:57 PM And it's not what I need.

Thanks for help.

It is parsed correctly (as 4 pm is 16) but it is your locale information which displays it differently than you want. You should use the following ToString method, which takes an IFormatProvider, in which you can pass in a CultureInfo that fits you.

Otherwise you can format your string using custom date and time formats like the following:

date.ToString("M/dd/yyyy HH:mm:ss")

It looks like it's parsing the string fine. You just want to display it in 24-hour format instead of 12-hour format (16:07:57 is the same as 4:07:57 PM). Try something like DateTime.Parse("16:07:57.796").ToString("M/d/yyyy H:mm:ss") .

It's correctly parsing it to the specified time on the current date.

If you don't want the current date, you can use the overload that takes a DateTimeStyles parameter, and specify DateTimeStyles.NoCurrentDateDefault . In this case, the date will be 01/01/0001.

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