StackTrace
StackTrace

Reputation: 9416

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);

Upvotes: 0

Views: 86

Answers (2)

0x49D1
0x49D1

Reputation: 8704

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

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460288

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.

Upvotes: 7

Related Questions