ParseExact / TryParseExact失败,只有一位数小时 [英] ParseExact/TryParseExact failing with single digit hour

查看:198
本文介绍了ParseExact / TryParseExact失败,只有一位数小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有字段定界符的时间和日期值,我正尝试使用 TryParseExact 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆