Home > Blockchain >  How can I parse ISO 8601's "PnDTnHnMn.nS" format in C#/.NET?
How can I parse ISO 8601's "PnDTnHnMn.nS" format in C#/.NET?

Time:10-22

I have a date value in windows console application like this one "P0Y0M0DT23H43M52.103S", and I want to parse this datetime value in c# to get minutes out of datetime value. It is easily done in Java by using new java.time.Duration.parse("P0Y0M0DT23H43M52.103S").toMinutes().

The documentation for Duration.parse(CharSequence text) says:

This will parse a textual representation of a duration, including the string produced by toString(). The formats accepted are based on the ISO-8601 duration format PnDTnHnMn.nS with days considered to be exactly 24 hours.

I am looking for a similar functionality in .net c# which can help me workout time in minutes accurately without having to run loop and split.

Thank you

CodePudding user response:

You can use my Noda Time library and its Period type:

using NodaTime;
using NodaTime.Text;

var parseResult = PeriodPattern.NormalizingIso.Parse("P0Y0M0DT23H43M52.103S");
if (parseResult.Success)
{
    Period period = parseResult.Value;
    Console.WriteLine($"Success! Parsed to {period}");
}

Note that even in Java, parsing an ISO-8601 period as a Duration is somewhat inappropriate... durations should be fixed lengths of time whereas if you have an ISO-8601 period of something like "P1M", that isn't a fixed length of time (ditto years). That's why the Duration.parse method requires it to only have days, hours, minutes etc.

CodePudding user response:

Use XmlConvert.ToTimeSpan():

TimeSpan duration = XmlConvert.ToTimeSpan("P0Y0M0DT23H43M52.103S");
  • Related