1

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);
Barak
  • 16,318
  • 9
  • 52
  • 84
Shami C
  • 87
  • 1
  • 7

5 Answers5

6

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

John Woo
  • 258,903
  • 69
  • 498
  • 492
  • No. Even that is not working. Error is String was not recognized as a valid DateTime. – Shami C Oct 18 '12 at 14:11
  • 1
    @ShamiC i just updated the answer, since you have added `tt`, it is not in `24-hr` format anymore. so change `HH` into `hh` – John Woo Oct 18 '12 at 14:13
  • @JohnWoo - And since `hh` expects a leading `0` for a single digit hour, you need to remove the extra `h`. – Oded Oct 18 '12 at 14:15
  • This is inaccurate without @Oded's correction. Why is it getting so many upvotes? (I downvoted) – Tim S. Oct 18 '12 at 14:16
  • @TimS. you're right. I updated it after Oded's correction. Am I not allow to update the answer? If I have the ability to change the upvotes of my answer. I will give it all to you. :) – John Woo Oct 18 '12 at 14:31
  • I suspect you need to replace `dd` with `d` too, since the OP probably wants to be able to parse single digit days. – CodesInChaos Oct 18 '12 at 14:33
3

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.

Tim S.
  • 55,448
  • 7
  • 96
  • 122
2

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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

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"
Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

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

Thom Smith
  • 13,916
  • 6
  • 45
  • 91