0

I am converting DateTime to a string in en-US culture.

dateTimeString = dateTime.ToString();

But if I start my app in fr-FR culture and try to parse using below statement

DateTime.Parse(dateTimeString, CultureInfo.CurrentCulture);

It throws FormatException.

I am missing something?

Gaddigesh
  • 1,953
  • 8
  • 30
  • 41

2 Answers2

2

Yes, that's going to be a problem.

The regular ToString() on a DateTime will generate a date string like this, for en-US:

"8/26/2012 8:54:16 PM"

For fr-FR it will generate this instead:

"26/08/2012 20:54:16"

So, if you try to parse the first string (en-US) as a fr-FR date time string, the 26 would be considered an invalid month and a FormatException is expected.

EDIT: Date/times can be a bit of a pain to work with. For portability (across culture formats and timezones), if you need to serialize as a string, I'd recommend serializing in ISO 8601 format.

jglouie
  • 12,523
  • 6
  • 48
  • 65
  • Do you have control of serializing the date in the first place? If so, store strings using ISO 8601 format – jglouie Aug 26 '12 at 21:03
  • More info on 8601 with .NET: http://stackoverflow.com/questions/114983/in-c-given-a-datetime-object-how-do-i-get-a-iso-8601-date-in-string-format – jglouie Aug 26 '12 at 21:04
  • Thanks for the link.... one more thought ...Can't i convert in invariant culture and retrieve in invariant culture? – Gaddigesh Aug 26 '12 at 21:16
  • 1
    Yes, you can convert and parse if you explicitly use the same culture. I'm not sure how portable the invariant approach is though (i.e. would Java be able to parse this easily?). Many languages have libraries to deal with 8601 format. – jglouie Aug 26 '12 at 21:24
  • I tried Invariant while saving and retrieving ...Working fine :-) – Gaddigesh Aug 26 '12 at 21:26
1

As jglouie states you can't parse a date time string in a different culture.

You are going to have to parse it using "en-US".

DateTime.Parse(dateTimeString, CultureInfo.CreateSpecificCulture("en-US"));

There's no other way round it.

The best solution might be to use the invariant culture when converting the DateTime to a string and when parsing the string back into a DateTime. This will give you consistent results regardless of the settings of the computer running the application.

Community
  • 1
  • 1
ChrisF
  • 134,786
  • 31
  • 255
  • 325