0

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

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i have made the change but still with that sample string, dt returns as "1/1/0001 12:00:00 AM"
It either throws an exption or returns a valid DateTime since you are not using DateTime.TryParseExact. So is it the real code that you've shown? If i test it it works for me.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.