10

Method TryParseExact in code block below returns true.
I would like to know why.
I think this date "2013.03.12" is invalid because this is not separated by slash but dot.

After I changed the CultureInfo "de-De" to "en-US", the method returns false. This could be a hint but I still don't know why this happens.

var format = new string[] { "yyyy/MM/dd" };
var parsed = new DateTime();
var result = DateTime.TryParseExact("2013.03.12", format, 
             new CultureInfo("de-DE"), DateTimeStyles.None, out parsed);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Nigiri
  • 3,469
  • 6
  • 29
  • 52

2 Answers2

17

I think your current DateSeparator is . (dot) and / automatically replace itself to it.

/ separator has a special meaning of "replace me with the current culture's date separator".

CultureInfo c = new CultureInfo("de-DE");
Console.WriteLine(c.DateTimeFormat.DateSeparator); //Prints . (dot)

Take a look at the "/" Custom Format Specifier.

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • @lazyberezovsky Yeah, I wasn't aware of this either since Tim Schmelter [points](http://stackoverflow.com/questions/17526239/converting-datetime-to-string/17526314#comment25485437_17526239) this situation almost a month ago. – Soner Gönül Aug 21 '13 at 06:41
  • 1
    Thank you so much. Sometimes, I don't have to define formats by country in this specification. – Nigiri Aug 21 '13 at 07:12
7

As @Soner Gönül points out, the / is taken as "the date separator" in custom format strings. If you want to only accept / characters, you need to escape them:

var format = new string[] { @"yyyy\/MM\/dd" };
Community
  • 1
  • 1
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448