Parsing the ISO-8601 duration values of the AMAZON.DURATION slot type

Viewed 4248

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))
3 Answers
Related