While struggling with DateTime.ParseExact formatting issues, I decided to feed ParseExact the out put from DateTime.ToString(), like this:
DateTime date2 = new DateTime(1962, 1, 27);
string[] expectedFormats = { "G", "g", "f", "F", "D", "d", "M/d/yyy", "MM/dd/yyy", "MM-dd-yyy", "MMM dd, yyy", "MMM dd yyy", "MMMM dd, yyy", "MMMM dd yyy" };
bool parsed = false;
foreach (string fmt in expectedFormats)
{
try
{
DateTime dtDateTime = DateTime.ParseExact(date2.ToString(fmt), fmt, new CultureInfo("en-US"));
parsed = true;
}
catch (Exception)
{
parsed = false;
}
Console.WriteLine("[{0}] {1}", parsed,date2.ToString(fmt));
}
This is the output:
[True] 1/27/1962 12:00:00 AM
[True] 1/27/1962 12:00 AM
[True] Saturday, January 27, 1962 12:00 AM
[True] Saturday, January 27, 1962 12:00:00 AM
[True] Saturday, January 27, 1962
[True] 1/27/1962
[False] 1/27/1962
[False] 01/27/1962
[False] 01-27-1962
[False] Jan 27, 1962
[False] Jan 27 1962
[False] January 27, 1962
[False] January 27 1962
What do I have to do so that ParseExact will parse the custom format strings? Am I wrong to expect DateTime to be able to ingest it's own output based on the same format string?
This clearly demonstrates that DateTime.ParseExact
is not round-trip safe with Datetime.ToString
. I am not sure this is much of an answer, but the problem is definitely related to the 3 digit year format yyy
. Since 1962 cannot be represented in 3 digits ToString
is forced to use 4 digits. Apparently ParseExact
is not smart enough to reverse that logic and instead is looking for exactly 3 digits. The workaround is to use yyyy
instead of yyy
. I would submit this as a bug to the Microsoft Connect website and see what comes of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With