简体   繁体   中英

Weird DateTime parsing behaviour

I am noticing this weird behavior when parsing 2 string to DateTime. The first string (causes exception) "20/10/2013 3:08:30 AM" The second string (converts correctly with no exceptions) "9/10/2013 3:09:37 AM"

The code used to convert is :

string date_1 = "20/10/2013 3:08:30 AM";
string date_2 = "9/10/2013 3:09:37 AM"; 
try
{
DateTime d1 = DateTime.parse(date_1, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);   //throws exception (String was not recognized as a valid DateTime)
} catch (Exception ex) { throw ex; }
DateTime d2 =  DateTime.parse(date_2, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

Can anybody please explain why 2 strings representing full date with the same format do this?

Thank you all in advance.

This will throw because US date notation expects month as first field:

string d = "20/10/2013 3:08:00 AM";
Console.WriteLine(DateTime.Parse(d, new CultureInfo("en-US")));

Same for InvariantCulture.

This will work:

DateTime.Parse(d, new CultureInfo("nl-NL"))

You need to specify the culture when parsing a date. If your computers location settings are correct for your region and so is the date then you can simply parse with the current culture.

Eg

string date = "20/10/2013 3:08:00 AM";    
Console.WriteLine(DateTime.Parse(date, CultureInfo.CurrentUICulture));

Or simply:

string date = "20/10/2013 3:08:00 AM";    
Console.WriteLine(DateTime.Parse(date));

This will work for me here in Australia, however if your regional settings are for the US for example then you would need to specify the culture you expect the date to be formatted in. Eg

string date = "20/10/2013 3:08:00 AM";    
Console.WriteLine(DateTime.Parse(date, new CurrentUICulture("en-AU")); //en-GB, etc

That being said it is quicker (and perhaps safer) to use DateTime.TryParse if you expect the date format to be incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM