stackUnderflow stackUnderflow - 2 months ago 12
Java Question

Parsing ISO 8601 duration format to Joda duration - IllegalArgumentException

I am trying to parse ISO 8601 duration of 1 month to Joda Duration object.
Can you please help me why this line of code

Duration duration = Duration.parse("P1M");


throws

java.lang.IllegalArgumentException: Invalid format: "P1M"
at org.joda.time.convert.StringConverter.getDurationMillis(StringConverter.java:111)
at org.joda.time.base.BaseDuration.<init>(BaseDuration.java:105)
at org.joda.time.Duration.<init>(Duration.java:209)
at org.joda.time.Duration.parse(Duration.java:59)

Answer

In this case, it should be a Period not a Duration as it is one month long so try this instead:

Period period = Period.parse("P1M");

Indeed a Duration needs to be expressed in an exact amount of milliseconds and as a month cannot be exactly expressed in milliseconds as it changes from one month to another it cannot be a Duration.

More details about Period and Duration here