none
Single digit month does not work with DateTime.ParseExact RRS feed

  • Question

  • I am trying to parse a date string that I know is in the format of "Mddyy", but it throws an exception if the month is a single digit.  Why is this?  Is there a way that I can use ParseExact to do this without having to manipulate the date string before parsing it?

    This does not work..

     DateTime.ParseExact("91201", "Mddyy", CultureInfo.InvariantCulture)

    Though, this does work..

    DateTime.ParseExact("091201", "Mddyy", CultureInfo.InvariantCulture)

    • Moved by Mike DanesModerator Tuesday, December 4, 2012 7:12 PM BCL related (From:Common Language Runtime)
    Tuesday, December 4, 2012 4:40 PM

Answers

  • It's likely a limitation of ParseExact, the documentation has a note about lack of separators:

    "If format is a custom format pattern that does not include date or time separators (such as "yyyyMMdd HHmm"), use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the format pattern, specify the wider form, "HH", instead of the narrower form, "H"."

    Lack of separators coupled with the variable length of M probably make it difficult to simply parse the date string from left to right, for this to work the code would have to start from end (because at least in this case dd and yy happen to have constant length) or backtrack when reaching the end and discovering that there is one more digit that can be used. Not pretty.


    Tuesday, December 4, 2012 7:28 PM
    Moderator

All replies

  • Looks like a bug to me. Anyone else got ideas?

    "Premature optimization is the root of all evil." - Knuth

    If I provoked thought, please click the green arrow

    If I provoked Aha! please click Propose as Answer

    Tuesday, December 4, 2012 4:56 PM
  • It's likely a limitation of ParseExact, the documentation has a note about lack of separators:

    "If format is a custom format pattern that does not include date or time separators (such as "yyyyMMdd HHmm"), use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the format pattern, specify the wider form, "HH", instead of the narrower form, "H"."

    Lack of separators coupled with the variable length of M probably make it difficult to simply parse the date string from left to right, for this to work the code would have to start from end (because at least in this case dd and yy happen to have constant length) or backtrack when reaching the end and discovering that there is one more digit that can be used. Not pretty.


    Tuesday, December 4, 2012 7:28 PM
    Moderator