javajava-timedurationiso8601

Not able to parse P10YT10M ISO-8601 duration string in java


I am trying to parse durationString= P10YT10M using java.time.Duration.parse() method, but it fails with "Text cannot be parsed to a Duration".

try {
    String durationString = "P5YT30M";
    Duration duration = Duration.parse(durationString);
} catch ( Exception e) {
    System.err.println( e.getMessage());

It's working for durationStrings like PT5M, but it cannot parse durationStrings similar to P5YT30M, P5Y8M4W3D.


Solution

  • No, that text can't be parsed to a Duration. The documentation for Duration.parse is clear about what it will handle:

    Obtains a Duration from a text string such as PnDTnHnMn.nS.

    [...] There are then four sections, each consisting of a number and a suffix. The sections have suffixes in ASCII of "D", "H", "M" and "S" for days, hours, minutes and seconds, accepted in upper or lower case. The suffixes must occur in order.

    P10YT10M isn't in that format, so it can't be parsed by Duration.parse. There's a good reason for this: a Duration is a fixed length of time (and the Duration.parse docs call out that parse treats a day as 24 hours). Years and months are not fixed lengths of time - should "P1M" be equivalent to 28 days? 29? 30? 31?

    You can use Period.parse for non-time-based ISO durations, but that still won't handle P5YT30M for example. If you really need this, I'd suggest you:

    But before you write any code, it's worth figuring out your precise requirements. What do you want to do with the result? If you want to add it to a LocalDateTime for example, it would be better to keep the Period and Duration separate.