I have a date string that is coming in as what I believe to be Mddyyyy. However, TryParseExact doesn’t seem to be working. Here’s the sample 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");
}
That same code works if there’s a leading zero, but I would think then that the leading zero would only work with a formatting string of MMddyyyy.
Here I propose an explanation and provide evidence for the proposal.
Proposed Explanation: The parser internally uses the format string to create a regular expression that contains a greedy quantifier (which means, in this case, it prefers to match 2-digit months over 1-digit months). The
Min the OP’s format string becomes something like\d{1,2}(though that would match months numbered from 0 to 99!) in the parser’s internal regular expression.Evidence: If you move the month to the end of both the data and the format string, the greedy quantifier cannot obtain more than 1 digit and so it matches the month as desired:
Bottom Line: Don’t rely on undocumented behavior. Always use unambiguous data, i.e., 2-digit months.