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 ?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

3 Answers3

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

Vlad
  • 35,022
  • 6
  • 77
  • 199
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).

Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
  • I dont understand can you please explain ? – Royi Namir Apr 02 '12 at 14:43
  • 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. – Adriano Repetti Apr 02 '12 at 14:52
  • 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. – Adriano Repetti Apr 02 '12 at 14:59
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

Mikey Mouse
  • 2,968
  • 2
  • 26
  • 44