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

后端 未结 6 783
闹比i
闹比i 2020-12-03 22:07

I\'m trying out the DateTime.TryParseExact method, and I have come over a case that I just don\'t get. I have some formats and some subjects to parse that each

6条回答
  •  感动是毒
    2020-12-03 22:12

    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 :)

提交回复
热议问题