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.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With