DateTime.Parse: culture change exception

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

String was not recognized as a valid DateTime. 

I get this error only if I run the application from a computer located in a country other than the United States. What I see in the line 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 do not get an exception. I believe that this is the fact that day 20 has come and this computer is in Europe, so he believes that 20 is a month. The problem is that I force her to be in the USA:

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

Since I am getting an exception, I believe this is the right approach.

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

+7
c #
source share
1 answer

You should use "HH: mm" instead of "hh: mm" - "HH" - for a 24-hour clock; "hh" is designed for 12 hours. Thus, 14 is not a valid value for "hh".

I would expect to see the same problem even on an American car, although ... maybe you managed to get only up to 1 hour per minute on your cars in the USA due to differences in time zones?

+10
source share

All Articles