Why the call to DateTime.TryParseExact fails with the input "1212012" using the format string "Mddyyyy"

I have a date string that comes in as what I consider Mddyyyy. However, TryParseExact does not work. Here is an example of code that fails:

string datestring = "1212012"; DateTime td; if (DateTime.TryParseExact(datestring, "Mddyyyy", new CultureInfo("en-US"), DateTimeStyles.None, out td)) { Console.WriteLine(td.ToShortDateString()); } else { Console.WriteLine("Invalid Date String"); } 

The same code works if there is a leading zero, but I would have thought then that the leading zero would only work with the MMddyyyy format string.

+6
source share
1 answer

Here I offer an explanation and give evidence for this proposal.

Suggested explanation : The parser internally uses a format string to create a regular expression containing a greedy quantifier (meaning that in this case it prefers to match 2-digit months over a 1-digit month). M in the OP format string becomes something like \d{1,2} (although this will correspond to months from 0 to 99!) In the internal parser regular expression.

Proof . If you transfer the month to the end of both data and format strings, the greedy quantifier cannot receive more than 1 digit and therefore it matches the month as desired:

 string datestring = "2120121"; DateTime td; if (DateTime.TryParseExact(datestring, "ddyyyyM", new CultureInfo("en-US"), DateTimeStyles.None, out td)) { Console.WriteLine(td.ToShortDateString()); } else { Console.WriteLine("Invalid Date String"); } 

Bottom line . Do not rely on undocumented behavior. Always use unambiguous data, i.e. 2-digit months.

+3
source

Source: https://habr.com/ru/post/910382/


All Articles