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

3

8

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 ?

Oscillator answered 2/4, 2012 at 14:34 Comment(1)
Short version: You didn't specify / or :Megasporangium
C
9

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

Closet answered 2/4, 2012 at 14:37 Comment(3)
it's German (de-DE) for Monday (but perhaps you could share the image with us?)Closet
if montag is monday so what is 2. ?Oscillator
@Royi: the number of day in the month.Closet
M
4

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

Misshape answered 2/4, 2012 at 14:41 Comment(3)
I dont understand can you please explain ?Oscillator
the string "M/d/yyyy" is a format specifier for "4/2/2012" in en-US culture but is a valid input, for example, "4-2-2012" for Arabic culture too. The "/" character means "the default date separator for the given culture". Anyway I updated the answer with an example.Misshape
no...it's just a format, it'll replace "/" with its actual value according with the given culture. If it must be exact you have to escape.Misshape
S
0

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

Silda answered 2/4, 2012 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.