DateTime and localization

  • Thread starter Thread starter akiecker
  • Start date Start date
A

akiecker

I have a string representing the date in US format (mm/dd/yyyy). I use
Convert.ToDateTime() to convert this to a DateTime structure. I then compare
this to the current date DateTime.ToDay.

All works fine until the localization is changed, for example to Germany,
then the string representing the date is incorrectly interpreted as if it
were in the local format dd/mm/yyyy (or is it dd-mm-yyyy) with a resulting
incorrect value for the DateTime with a resultant invalid comparison to the
current date.

Any suggestions on how to handle this would be appreciated.

Is there some way that I can specify that my string should be converted to a
DateTime structure using the “en_US†culture?

Thankyou.
 
Is there some way that I can specify that my string should be converted to a
DateTime structure using the “en_US” culture?

Use one of the ToString overloads that let you supply a
DateTimeFormatInfo so you can set the format.

Dave
 
I have a string representing the date in US format (mm/dd/yyyy). I use
Convert.ToDateTime() to convert this to a DateTime structure. I then
compare this to the current date DateTime.ToDay.

General rule: all processing should happen on locale-insensitive data,
all user-visible items should be locale-sensitive.

If the string comes from from user, it should be converted to a structure
using the user preferences (CurentCulture) and DateTime.TryParse or
DateTime.TryParseExact.
If the string comes from another module, then you can either use a
CultureInvariant, or pass a your format to TryParseExact.

The current format (mm/dd/yyyy) strikes me as "very American,"
and if you have control on the module generating that I woul recoment
moving to the iso format (yyyy.mm.dd), which is more "locale-independent"

See also here: http://www.mihai-nita.net/article.php?artID=20051025a
 
Back
Top