Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to DateTime with pattern "MM/dd/yyyy hh:mm:ss"

Tags:

date

c#

datetime

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!

like image 443
SoumaZ Avatar asked Apr 01 '26 06:04

SoumaZ


2 Answers

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);
  • The "/" Custom Format Specifier *
like image 83
Tim Schmelter Avatar answered Apr 03 '26 20:04

Tim Schmelter


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

like image 38
Soner Gönül Avatar answered Apr 03 '26 19:04

Soner Gönül



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!