ParseExact/TryParseExact failing with single digit hour

Viewed 1259

I have a time and a date value with no field delimiters which I'm attempting to parse into a DateTime using TryParseExact. The time component has a single digit hour, and two digit minutes and seconds.

The following expression:

DateTime.ParseExact("20170101 84457", "yyyyMMdd Hmmss", 
    System.Globalization.CultureInfo.InvariantCulture)

results in FormatException with the message "String was not recognized as a valid DateTime.". I am assuming that this is because the time can't be unambiguously resolved, however since mm and ss are always going to be two digits each, I don't understand why this would be an issue.

The following results in successful parsing:

  • Hacking the input time to include delimiters (e.g., '8:44:57' and 'H:mm:ss')
  • Kludging the input time to have a leading zero if < 6 digits

Both of these seem a bit of a hack.

2 Answers
Related