I've been parsing ISO8601 TimeSpan values for a while now, until I encountered one that caused my code to throw a System.FormatException:
TimeSpan ts = XmlConvert.ToTimeSpan("P2M2W5D");
Looking at the ISO8601 Standard, it seems to be a correct input, and also without any ambiguities (the M clearly refers to months, not minutes).
System.FormatException was unhandled by user code
HResult=-2146233033
Message=The string 'P2M2W5D' is not a valid TimeSpan value.
Source=System.Xml
From XmlConvert.ToTimeSpan
method
Parameters
s Type: System.String
The string to convert. The string format must conform to the W3C XML Schema Part 2: Datatypes recommendation for duration.
And Duration section
The lexical representation for duration is the [ISO 8601] extended format
PnYn MnDTnH nMnS
, wherenY
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 andnS
the number of seconds.
From ISO 8601 Date and Time Formats
In the lexical format for duration the following characters are also used as designators and appear as themselves in lexical formats:
- P -- is used as the time duration designator, preceding a data element representing a given duration of time.
- Y -- follows the number of years in a time duration.
- M -- follows the number of months or minutes in a time duration.
- D -- follows the number of days in a time duration.
- H -- follows the number of hours in a time duration.
- S -- follows the number of seconds in a time duration.
As far as I can see, there is no W
as a duration format in XML specification.
This works for example;
TimeSpan ts = XmlConvert.ToTimeSpan("P2M5D");
TimeSpan
can not handle this because of the months being specified. TimeSpan
is just a number of ticks. Since the number of days in a month varies it cannot be converted to a tick.
The other issue is that 'W' (week) is defined in ISO 8601 but not in the XML spec, so XmlConvert doesn't know about it.
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