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?
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);

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;
/ as a DateSeparator or: as a TimeSeparator orGregorianCalendar as a Calendar property orAM or PM as a PMDesignator or AMDesignator properties.For those, your ParseExact method throws exception even if your string and format perfectly matches.
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