如何将 ISO8601 时间跨度转换为 C# 时间跨度? [英] How do I convert an ISO8601 TimeSpan to a C# TimeSpan?

查看:28
本文介绍了如何将 ISO8601 时间跨度转换为 C# 时间跨度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试执行以下操作(作为示例)时,我收到 System.FormatException:

I am getting a System.FormatException when I try to do the following (as an example):

TimeSpan ts = XmlConvert.ToTimeSpan("P72H");

我调查了 ISO8601 标准,它似乎是正确的,但我无论我做什么,都无法在不抛出异常的情况下解析数小时.

I've investigated the ISO8601 Standard and it seems to be correct, but I cannot get it to parse hours without throwing an exception, no matter what I do.

谢谢!

异常详情:

System.FormatException was unhandled by user code
HResult=-2146233033
Message=The string 'P72H' is not a valid TimeSpan value.
Source=System.Xml

推荐答案

您需要在字符串中添加时间分隔符.试试这个:

You need to add the Time separator to your string. Try this:

TimeSpan ts = XmlConvert.ToTimeSpan("PT72H");

查看持续时间规范 - http://www.w3.org/TR/xmlschema-2/#duration

See the duration specification - http://www.w3.org/TR/xmlschema-2/#duration

3.2.6.1 词法表示
持续时间的词汇表示是 [ISO 8601] 扩展格式 PnYn MnDTnH nMnS,其中 nY 表示年数,nM 月数,nD 天数,'T' 是日期/时间分隔符,nH 数小时数,nM 分钟数,nS 秒数.秒数可以包含任意精度的十进制数字.

3.2.6.1 Lexical representation
The lexical representation for duration is the [ISO 8601] extended format PnYn MnDTnH nMnS, where nY represents the number of years, nM the number of months, nD the number of days, 'T' is the date/time separator, nH the number of hours, nM the number of minutes and nS the number of seconds. The number of seconds can include decimal digits to arbitrary precision.

根据评论编辑/更新

因为有一些关于为什么字符串 P2M2W5D 不被视为有效的 TimeSpan 的问题,因为 W 是 ISO 8601 的一部分标准,我想添加此更新,以便如果有人遇到该问题,他们不必通读评论即可获得答案.有问题的原始字符串 P72HP2M2W5D 的问题是该字符串必须符合 W3C XML 模式(请参阅 XmlConvert.ToTimeSpan).当我们查看 W3C XML Schema(上面的链接)时,它引用了 ISO 8601 标准,特别是第 5.5.3.2.1 节,它给出了 W 不是有效字符的原因在 XML 架构中:

As there was some question as to why the string P2M2W5D would not be considered a valid TimeSpan since W is part of the ISO 8601 standard, I wanted to add this update so that if someone runs across that issue they don't have to read through the comments to get the answer. The issue, both for the original string in question P72H and P2M2W5D is that the string must conform to the W3C XML Schema (see the documentation for XmlConvert.ToTimeSpan). When we look at the W3C XML Schema (link above), it references back to the ISO 8601 standard, and in particular to section 5.5.3.2.1 which gives the reason why W is not a valid character in the XML Schema:

由于周没有定义的结转点(52 或 53),因此周应该不得在这些应用程序中使用

Since weeks have no defined carry-over point (52 or 53), weeks should not be used in these applications

这篇关于如何将 ISO8601 时间跨度转换为 C# 时间跨度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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