Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a specific ISO8601 TimeSpan ("P2M2W5D") to a C# TimeSpan [duplicate]

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
like image 697
Alexandru Marculescu Avatar asked Dec 20 '22 00:12

Alexandru Marculescu


2 Answers

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, 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.

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

enter image description here

like image 192
Soner Gönül Avatar answered Mar 30 '23 00:03

Soner Gönül


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.

like image 41
Richard Schneider Avatar answered Mar 30 '23 01:03

Richard Schneider