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

后端 未结 6 782
闹比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:11

    I could be wrong, but I suspect it may have to do with the ambiguity inherent in the "H" part of your format string -- i.e., given the string "123", you could be dealing with hour "1" (01:00) or hour "12" (12:00); and since TryParseExact doesn't know which is correct, it returns false.

    As for why the method does not supply a "best guess": the documentation is not on your side on this one, I'm afraid. From the MSDN documentation on DateTime.TryParse (emphasis mine):

    When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or DateTime.MinValue if the conversion failed. The conversion fails if either the s or format parameter is null, is an empty string, or does not contain a date and time that correspond to the pattern specified in format. This parameter is passed uninitialized.

提交回复
热议问题