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!
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);
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
CultureInfoobject 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With