Does the java.time
library provide a consolidated way to parse the entire ISO-8601 Duration Specification?
The Alexa Slot Type reference for duration lists some example strings to expect when using the AMAZON.DURATION slot type. All strings are in ISO-8601 Duration, but P2YT3H10
cannot be parsed by either java.time.Period
or java.time.Duration
.
Seq(
"PT10M",
"PT5H",
"P3D",
"PT45S",
"P8W",
"P7Y",
"PT5H10M",
"P2YT3H10"
).map { s =>
s -> Try {
try {
Period.parse(s)
} catch {
case ex: Throwable => Duration.parse(s)
}
}.map(x => x.toString -> x.getClass.getSimpleName)
}
.foreach(println)
Results:
(PT10M,Success((PT10M,Duration)))
(PT5H,Success((PT5H,Duration)))
(P3D,Success((P3D,Period)))
(PT45S,Success((PT45S,Duration)))
(P8W,Success((P56D,Period)))
(P7Y,Success((P7Y,Period)))
(PT5H10M,Success((PT5H10M,Duration)))
(P2YT3H10,Failure(java.time.format.DateTimeParseException: Text cannot be parsed to a Duration))
Hugos answer is only related to one detail aspect of the ISO-8601-standard, namely the combination of date and time part with a "T"-separator. This detail is indeed not supported by
java.time
but supported by the external library Threeten-Extra (using the classPeriodDuration
in the version v1.2). However:The ISO-8601-standard describes even more variations.
One variation is the usage of weeks in the form "P8W". Both
java.time
and Threeten-Extra automatically change it to "P56D" but don't leave it in week-related form when parsing and formatting. A similar view can be obtained when looking at the time components.java.time.Duration
cannot directly store hours or minutes but automatically convert it to seconds. When formatting an automatical normalization is performed, too. Example:So in both cases: What you put inside during construction is not always what you get when formatting.
Other points:
java.time
uses two different terms, namelyPeriod
andDuration
(either date-related or time-related).java.time
allows signs even inside the representations and interprete signs as component-related. Note that XML-Schema only handles signs preceding the whole duration expression (before "P"), that is not component-related but duration-related.java.time.Duration
only supports the dot.Finally we can state:
The ISO-8601-standard is only partially supported by
java.time
(and Threeten-Extra which only supports the combination of the classesPeriod
andjava.time.Duration
as additional detail).Alternative solution for true ISO-8601-support:
If you want or even need to overcome the limitations baked into
java.time
then you can use my library Time4J which supports all the additional details of ISO-8601. See the API of class net.time4j.Duration. Following examples also show the compatibility withjava.time
:Side note: Formatting of durations is possible in actually 86 languages.