Shami C
Shami C

Reputation: 87

Conversion from String to DateTime in C#

I want to convert a String to Datetime. I'm getting an error This is not a valid datetime.

The string I want to convert and code are as follows.

string date1 = "9/13/2012 5:26:06 PM";
TimePart = DateTime.ParseExact(date1, "M/d/yyyy HH:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);

Upvotes: 1

Views: 354

Answers (5)

Tim Schmelter
Tim Schmelter

Reputation: 460028

You need to use the lowercase h:

DateTime TimePart = DateTime.ParseExact(
                                date1,
                                "M/d/yyyy h:mm:ss tt",
                                CultureInfo.InvariantCulture);

Console.WriteLine(TimePart); // 09/13/2012 17:26:06

Uppercase "H" is 24-hour time, lowercase "h" is 12-hour time with AM/PM.

Upvotes: 2

John Woo
John Woo

Reputation: 263683

I think it should be M/dd/yyyy h:mm:ss tt in your format parameter.

Upvotes: 6

Oded
Oded

Reputation: 498904

You should be using a lower case h for a 12 hour clock (since you have an AM/PM designator).

Additionally, you should only use one h, as you don't have a leading 0 to the hours, and hh expects it.

A format string that works:

"M/d/yyyy h:mm:ss tt"

Upvotes: 2

Tim S.
Tim S.

Reputation: 56536

It looks like your format is really M/d/yyyy h:mm:ss tt. The difference is h (12-hour, with only as many digits as needed) instead of HH (24-hour, with leading 0 to pad to 2 digits).

If the input format can vary at all, you should use DateTime.Parse instead so that you don't have to tell it the exact format. ParseExact is faster, and requires that it matches the specified format, which may be preferable in your cast.

Upvotes: 3

Thom Smith
Thom Smith

Reputation: 14086

It looks like the HH isn't matching the "5". Try h.

Upvotes: 1

Related Questions