Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Parse: exception when changing culture

Tags:

c#

.net

I am parsing a string to convert it into a DateTime. I am getting in some cases an error:

String was not recognized as a valid DateTime.

I am getting this error only if I run the application from a computer located in a different country than US. What I see in the string is 09/20/2010 14:11 and in this case I get an exception. If I have a value like: 10/05/2010 12:54 I don't get an exception. I suppose it is the fact that the day is 20 and this computer is in Europe, so it thinks that 20 is the month. The problem is I force it to be en-US:

CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy hh:mm", new CultureInfo("en-US"));

Because I am getting the exception I suppose sure this is the correct approach.

Any idea how to parse a string in a way that works no matter what culture I am running on the machine?

like image 778
tony Avatar asked Oct 05 '10 18:10

tony


1 Answers

You should use "HH:mm" instead of "hh:mm" - "HH" is for 24-hour clock; "hh" is for a 12-hour clock. So 14 isn't a valid value for "hh".

I'd expect to see the same problem even on a US machine though... maybe you happened to only get pre-1pm times on your US machines due to time zone differences?

like image 109
Jon Skeet Avatar answered Sep 21 '22 18:09

Jon Skeet