.NET: Why is TryParseExact failing on Hmm and Hmmss?

Ok, so I think I have figured this all out now thanks to more reading, experimenting and the other helpful answers here. What’s happening is that H, m and s actually grabs two digits when they can, even if there won’t be enough digits for the rest of the format. So for example with the format Hmm and the digits 123, H would grab 12 and there would only be a 3 left. And mm requires two digits, so it fails. Tadaa.

So, my solution is currently to instead use just the following three formats:

var formats = new[]
    {
        "%H",
        "Hm",
        "Hms",
    };

With the rest of the code from my question staying the same, I will then get this as a result:

1      : 01:00:00
12     : 12:00:00
123    : 12:03:00
1234   : 12:34:00
12345  : 12:34:05
123456 : 12:34:56

Which I think should be both reasonable and acceptable 🙂

Leave a Comment