将特定的 ISO8601 TimeSpan ("P2M2W5D") 转换为 C# TimeSpan

Converting a specific ISO8601 TimeSpan ("P2M2W5D") to a C# TimeSpan

我解析 ISO8601 TimeSpan 值已经有一段时间了,直到我遇到一个导致我的代码抛出 System.FormatException:

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

ISO8601 Standard,好像输入正确,也没有歧义(M明明是月,不是分)。

System.FormatException was unhandled by user code
HResult=-2146233033
Message=The string 'P2M2W5D' is not a valid TimeSpan value.
Source=System.Xml
由于指定了月份,

TimeSpan 无法处理此问题。 TimeSpan 只是一些滴答声。由于一个月中的天数不同,因此无法转换为刻度。

另一个问题是 'W'(周)在 ISO 8601 中定义,但在 XML 规范中没有定义,因此 XmlConvert 不知道它。

来自XmlConvert.ToTimeSpan method

Parameters

s Type: System.String

The string to convert. The string format must conform to the W3C XML Schema Part 2: Datatypes recommendation for duration.

Duration section

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.

来自ISO 8601 Date and Time Formats

In the lexical format for duration the following characters are also used as designators and appear as themselves in lexical formats:

  • P -- is used as the time duration designator, preceding a data element representing a given duration of time.
  • Y -- follows the number of years in a time duration.
  • M -- follows the number of months or minutes in a time duration.
  • D -- follows the number of days in a time duration.
  • H -- follows the number of hours in a time duration.
  • S -- follows the number of seconds in a time duration.

据我所知,XML 规范中没有 W 作为持续时间格式。

例如,这有效;

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