Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't DateTime.ParseExact parse DateTime output?

Tags:

c#

.net

datetime

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?

like image 728
Greg Miskin Avatar asked Jul 23 '10 18:07

Greg Miskin


1 Answers

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.

like image 102
Brian Gideon Avatar answered Sep 20 '22 22:09

Brian Gideon