Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 833
Royi Namir Avatar asked Apr 02 '12 14:04

Royi Namir


2 Answers

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).

like image 128
Vlad Avatar answered Nov 07 '22 17:11

Vlad


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).

like image 4
Adriano Repetti Avatar answered Nov 07 '22 18:11

Adriano Repetti