简体   繁体   中英

Converting this string format to a valid DateTime?

The string in question: "2003:12:14 12:01:44" (yyyy:MM:dd hh:mm:ss)

How would I be able to convert this to a valid datetime in C#? I tried Convert.ToDateTime(str) , but to no avail.

Use the right DateTime format and supply DateTime.ParseExact with that format. Note that since your time doesn't show AM or PM, it may be safer to assume that it uses 24-Hr format (use capital HH ) than 12-Hr AM PM (not hh ) format. The following code should work:

string format = "yyyy:MM:dd HH:mm:ss"; //note: use HH not hh
var result = DateTime.ParseExact("2003:12:14 12:01:44", format, CultureInfo.InvariantCulture);

Check more on the available DateTime formats here (standard) and here (custom).

Convert.ToDateTime try to parse your string as a standard date and time format of your CurrentCulture settings. Looks like this string is not a standard format.

You can use DateTime.ParseExact for specify custom format.

var dt = DateTime.ParseExact("2003:12:14 12:01:44", 
                             "yyyy:MM:dd hh:mm:ss", 
                             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