問題描述
當我嘗試執(zhí)行以下操作(例如)時,我得到了一個 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");
查看持續(xù)時間規(guī)范 - http://www.w3.org/TR/xmlschema-2/#duration
See the duration specification - http://www.w3.org/TR/xmlschema-2/#duration
3.2.6.1 詞法表示
持續(xù)時間的詞法表示是 [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 的一部分標準,我想添加此更新,以便如果有人遇到該問題,他們不必通讀評論即可獲得答案.對于有問題的原始字符串 P72H
和 P2M2W5D
的問題是該字符串必須符合 W3C XML Schema(請參閱 XmlConvert.ToTimeSpan).當我們查看 W3C XML Schema(上面的鏈接)時,它引用了 ISO 8601 標準,特別是第 5.5.3.2.1 節(jié),它給出了 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 TimeSpan 轉換為 C# TimeSpan?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!