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.
source share