Search code examples
c#datetimestring-parsing

DateTime.ParseExact - how to parse single- and double-digit hours with same format string?


I want to be able to parse strings of time (hours, minutes, seconds) where the hours run from 0 to 23, and where the preceding zero for one-digit hours is optional.

Examples of time strings that I want to be able to parse into valid DateTime objects:

  • 212540
  • 061525
  • 94505

I am trying to use the C# method DateTime.ParseExact to manage the parsing, but I cannot for the life of it come up with a format string that can handle the "single-digit hour without preceding zero" scenario.

How should I specify the DateTime.ParseExact format string to sufficiently parse all examples above with the same line of code?

Inspired by the MSDN page on custom date and time formats, I have tried the following approaches:

DateTime.ParseExact(time_string, "Hmmss", CultureInfo.InvariantCulture);
DateTime.ParseExact(time_string, "%Hmmss", CultureInfo.InvariantCulture);
DateTime.ParseExact(time_string, "HHmmss", CultureInfo.InvariantCulture);

All these format strings work for the first two example cases above, but faced with a single-digit hour and no preceding zero, all formulations throw a FormatException.


Solution

  • You could pad your input string if you know that you'll always have six characters.

    string input = "94505";
    if(input.Length < 6)
       input = input.PadLeft(6, '0');
    

    (Or use input.Length == 5 if you have other valid formats that are shorter).