2

I have a string variable containing "02/27/2014 23:00:28" When I use this following code to convert it to Datetime type, the conversion fails (test returns false and parsedDate contains "01/01/0001 00:00:00")

code:

string date = "02/27/2014 23:00:28"
string pattern = "MM/dd/yyyy hh:mm:ss";
DateTime parsedDate;
bool parsedSuccessfully = DateTime.TryParseExact(date, pattern, null, DateTimeStyles.None, out parsedDate);

Thank you!

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
SoumaZ
  • 629
  • 1
  • 7
  • 14
  • BTW I guess you would wanna send the `date` variable into `DateTime.TryParseExact` method, not the `test` itself =) – Batu.Khan Apr 09 '14 at 11:39

3 Answers3

5

You need to use uppercase HH for the hours since you are using 24h format.

MM/dd/yyyy HH:mm:ss

You also need to use CultureInfo.InvariantCulture instead of null to ensure that / will be used as date separator. Otherwise it is replaced by your cultures actual date separator. *

bool test = DateTime.TryParseExact(date, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

hh specifier is for 01 to 12.

Use HH specifier which is for 00 to 23. (24-hour clock based)

And I think you should use date instead of test in your DateTime.TryParseExact method.

string date = "02/27/2014 23:00:28";
string pattern = "MM/dd/yyyy HH:mm:ss";
DateTime parsedDate;
bool test= DateTime.TryParseExact(date, pattern,
                                  CultureInfo.InvariantCulture,
                                  DateTimeStyles.None, out parsedDate);
Console.WriteLine(test); // True

Since you using null in your IFormatProvider parameter, it uses CurrentCulture. From documentation;

If provider is null, the CultureInfo object that corresponds to the current culture is used.

But / format specifier has a special meaning of "replace me with the current culture date seperator" in your string format.

That means, if your current culture's date separator is not /, your parsing operation will be fail. That's why you should use InvariantCulture in such a case.

Here an another answer: TryParseExact returns false, though I don't know why

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
2

24-hour time format uses HH. So your format should be

"MM/dd/yyyy HH:mm:ss"
Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99