Gaddigesh
Gaddigesh

Reputation: 1953

dateTimeString saved in en-US culture throws Format Exception while parsing in fr-FR culture

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?

Upvotes: 0

Views: 247

Answers (2)

ChrisF
ChrisF

Reputation: 137148

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.

Upvotes: 1

jglouie
jglouie

Reputation: 12880

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.

Upvotes: 2

Related Questions