Royi Namir
Royi Namir

Reputation: 148624

Why does TryParseExact require CultureInfo if I specify the exact structure?

Looking at

DateTime.TryParseExact(dateString, "M/d/yyyy hh:mm:ss tt",
                           CultureInfo.InvariantCulture, 0, out dateValue)

I supplied the exact structure to look for : M/d/yyyy hh:mm:ss tt

Question

If so , Why should I need to specify CultureInfo also ?

Upvotes: 8

Views: 1290

Answers (3)

Adriano Repetti
Adriano Repetti

Reputation: 67108

Because the format string is not literal. For example you used "/" and ":" but for the input string is required to use the date and time separators supplied by the CultureInfo.

Imagine this format string: M/d/yyyy
These inputs are all valid:

  • 04/02/2012 (for invariant culture, USA);
  • 04.02.2012 (for Finland)
  • 04-02-2012 (for Morocco)

Moreover the simple "M" specifier can be [1..12] or [1..13], depending on the calendar itself (see MSDN).

As "candle on the cake" the function is generic so you may require in the format string a localized (or country dependant) value (think about weekday names or the year specified, for example, in Chinese or in Japanese).

Upvotes: 4

Vlad
Vlad

Reputation: 35594

Well, month names can be localized, too. And perhaps in some exotic cultures the years are counted in a different way as well.

EDIT:
Example:

string x = "Montag, 2. April 2012";
DateTime dt1, dt2;
bool r1 = DateTime.TryParseExact(x, "D", new CultureInfo("de-DE"), 0, out dt1);
bool r2 = DateTime.TryParseExact(x, "D", new CultureInfo("en-US"), 0, out dt2);

(r1 == true, r2 == false).

Or, other way round:

string y = "Monday, April 02, 2012";
DateTime dt3, dt3;
bool r3 = DateTime.TryParseExact(y, "D", new CultureInfo("de-DE"), 0, out dt3);
bool r4 = DateTime.TryParseExact(y, "D", new CultureInfo("en-US"), 0, out dt4);

(r3 == false, r2 == true).

Upvotes: 9

Mikey Mouse
Mikey Mouse

Reputation: 3098

You need to tell it the culture, because if you pass it the format dd-mmm-yyyy then pass in 01/05/2012

In english that might be 01-May-2012

But in another culture it would be 01-Mai-2012

Upvotes: 0

Related Questions