且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何转换的时间跨度ISO8601为C#时间跨度?

更新时间:2023-02-26 16:20:59

您需要的时间分隔符添加到您的字符串。试试这个:

 时间跨度TS = XmlConvert.ToTimeSpan(PT72H);

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


  

3.2.6.1词汇重新presentation结果
  持续时间的词汇重新presentation是[ISO 8601]扩展格式PnYn MnDTnH NMNS,在纽约重新presents的年数,NM月数,第二的天数,T是日期/时间分隔,NH的小时数,纳米分钟的纳秒数和秒数。秒数可以包含小数位数任意precision。


块引用>

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

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

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.

Thanks!

EDIT:

Exception detail:

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");

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

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.