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 set the exact structure for the search: M/d/yyyy hh:mm:ss tt

Question

If so, why should I also specify CultureInfo ?

+7
source share
3 answers

Well, monthly names can also be localized. And, perhaps, in some exotic cultures years are counted in a different way.

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 vice versa:

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

+9
source

Because the format string is not literal. For example, you used "/" and ":", but the input string requires the date and time provided by CultureInfo .

Imagine this format string: M / d / yyyy
All of these inputs are valid:

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

Moreover, a simple โ€œMโ€ specifier can be [1..12] or [1..13], depending on the calendar itself (see MSDN).

As a โ€œcandle on the cakeโ€, the function is general, so you can require a localized (or country-specific) value in the format string (think about the names of the days of the week or the specified year, for example, in Chinese or Japanese).

+4
source

You have to say this to the culture, because if you give it the dd-mmm-yyyy format then go to 01/05/2012

In English, which may be 01-May-2012

But in a different culture, it will be 01-May-2012

0
source

All Articles