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.
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 asPnDTnHnMn.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:
Period
and the hours-and-smaller part as a Duration
Duration
to be for non-uniform parts like years and months. (For example, you could add the period to 2000-01-01 and work out the days since then in the result.)Duration
results togetherBut 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.