Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 765
Alexander Nikolov Avatar asked Sep 09 '16 12:09

Alexander Nikolov


2 Answers

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

like image 169
Nicolas Filotto Avatar answered Nov 28 '22 20:11

Nicolas Filotto


The Duration is used to represent time-based amount of time, like seconds and nanoseconds.

To represent data-based amount of time, you should consider use Period.

like image 28
Danilo Guimaraes Avatar answered Nov 28 '22 19:11

Danilo Guimaraes