Codeman Codeman - 1 year ago 212
C# Question

How do I convert an ISO8601 TimeSpan to a C# TimeSpan?

I am getting a

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.



Exception detail:

System.FormatException was unhandled by user code


Message=The string 'P72H' is not a valid TimeSpan value.


Answer Source

You need to add the Time separator to your string. Try this:

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

See the duration specification - 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download