Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert ISO 8601 Duration to TimeSpan in VB.Net?

Tags:

.net

xml

timespan

Is there a standard library method that converts a string that has duration in the standard ISO 8601 Duration (also used in XSD for its duration type) format into the .NET TimeSpan object?

For example, P0DT1H0M0S which represents a duration of one hour, is converted into New TimeSpan(0,1,0,0,0).

A Reverse converter does exist which works as follows: Xml.XmlConvert.ToString(New TimeSpan(0,1,0,0,0)) The above expression will return P0DT1H0M0S.

like image 331
Ralph Wiggum Avatar asked Sep 15 '08 13:09

Ralph Wiggum


2 Answers

This will convert from xs:duration to TimeSpan:

System.Xml.XmlConvert.ToTimeSpan("P0DT1H0M0S")

See http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.totimespan.aspx

like image 138
user7658 Avatar answered Oct 06 '22 00:10

user7658


One minor word of caution - XmlConvert.ToTimeSpan() is a little funny when working with months and years. The TimeSpan class does not have month or year members, probably because their length varies. However, ToTimeSpan() will happily accept a duration string with month or year values in it and guess at a duration, instead of throwing an exception. Observe:

PS C:\Users\troll> [Reflection.Assembly]::LoadWithPartialName("System.Xml")

GAC    Version        Location
---    -------        --------
True   v2.0.50727     C:\Windows\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c561934e089\System.Xml.dll


PS C:\Users\troll> [System.Xml.XmlConvert]::ToTimeSpan("P1M")


Days              : 30
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 25920000000000
TotalDays         : 30
TotalHours        : 720
TotalMinutes      : 43200
TotalSeconds      : 2592000
TotalMilliseconds : 2592000000



PS C:\Users\troll> [System.Xml.XmlConvert]::ToTimeSpan("P1Y")


Days              : 365
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 315360000000000
TotalDays         : 365
TotalHours        : 8760
TotalMinutes      : 525600
TotalSeconds      : 31536000
TotalMilliseconds : 31536000000



PS C:\Users\troll>
like image 21
Paul Williams Avatar answered Oct 05 '22 23:10

Paul Williams