ParseExact / TryParseExact失败,只有一位数小时 [英] ParseExact/TryParseExact failing with single digit hour
问题描述
我有一个没有字段定界符的时间和日期值,我正尝试使用 TryParseExact $ c解析为
DateTime
$ c>。时间部分具有一个数字小时和两个数字分钟和秒。
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.
以下表达式:
DateTime.ParseExact("20170101 84457", "yyyyMMdd Hmmss",
System.Globalization.CultureInfo.InvariantCulture)
导致 FormatException
并显示消息未将字符串识别为有效的DateTime。。我认为这是因为时间无法明确解决,但是由于 mm
和 ss
总是在运行都是两位数,我不明白为什么这会成为问题。
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.
以下结果成功解析:
- 输入时间不足以包含定界符(例如'8:44:57'和'H:mm:ss')
- 整理如果<<,则输入时间具有前导零。 6位数字
这两个数字似乎都有些骇人听闻。
Both of these seem a bit of a hack.
推荐答案
从其他人的研究,如果有可能,则尝试尝试检索两位数,然后从左到右进行解析。
From what I can understand from other people's research, parsing attempts to retrieve two digits if it can, and parses from left to right.
使用我失败的示例时间值 84857
的格式,格式为 Hmmss
,因为小时后跟一个数字,它将被解析为 84
-因此引发格式异常。
Using my failing example of the raw time value 84857
and format Hmmss
, because the hour is followed by a digit, it will be parsed as 84
- hence throwing a format exception.
这篇关于ParseExact / TryParseExact失败,只有一位数小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!