简体   繁体   中英

Converting string to DateTime failing

I have a string variable whose data will be the format below.

18-03-2015 16:39:15

i'm trying to convert it to a valid DateTime with hour/minute/second but so far the line below fails.

DateTime dt = DateTime.ParseExact("18-03-2015 16:39:15", "dd-MM-yyyy h:m:s", CultureInfo.InvariantCulture);

You need to use uppercase H or HH , so "dd-MM-yyyy HH:m:s" with this time: 16:39:15.

See: The "HH" Custom Format Specifier

So lowercase is from 1 through 12 and uppercase for 24h format. If you use H or HH depends on if 4:39:15 is possible or 04:39:15 . A single H supports both formats, so with or without a leading zero, whereas HH only allows 04:39:15 .

It should be HH:mm:ss in format

DateTime dt = DateTime.ParseExact("18-03-2015 16:39:15", "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
// So: dt.ToString("dd-MM-yyyy HH:mm:ss") is 18-03-2015 16:39:15

Here are some examples of formatting the date with samples

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