Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't DateTime.ParseExact work for this example outside of the US?

I have a string:

var stringDate = "8/19/2016 5:00:00 PM"

and I try using:

var dateTime = DateTime.ParseExact(stringDate,"M/d/yyyy h:mm:ss tt", null);

or

var dateTime = DateTime.ParseExact(stringDate, "M/d/yyyy h:mm:ss tt", 
                                   CultureInfo.Invariant);

or

var dateTime = DateTime.ParseExact(stringDate,"M/d/yyyy h:mm:ss tt",
                                   CultureInfo.GetCultureInfo("en-us"));

It works fine if the machine is in the US but and for all 3 options I get the following error when running from a machine in London:

String was not recognized as a valid DateTime

what am I missing here?

like image 529
leora Avatar asked Dec 02 '25 13:12

leora


1 Answers

As far as I can see, you need to use h specifier instead of hh specifier since your hour part does not have leading zero for single digit values.

var stringDate = "8/19/2016 5:00:00 PM";
var dateTime = DateTime.ParseExact(stringDate, "M/d/yyyy h:mm:ss tt",
                                   CultureInfo.InvariantCulture);

enter image description here

Also I would suggest to use specific culture settings instead of null for any case. In your example, since null means CurrentCulture settings for DateTime parsing methods, your CurrentCulture settings;

  • May not use / as a DateSeparator or
  • May not use : as a TimeSeparator or
  • May not use GregorianCalendar as a Calendar property or
  • May not have AM or PM as a PMDesignator or AMDesignator properties.

For those, your ParseExact method throws exception even if your string and format perfectly matches.

like image 139
Soner Gönül Avatar answered Dec 05 '25 04:12

Soner Gönül