I am having an issue with parsing the Duration
:
// import java.time.Duration;
...
Duration d = Duration.parse("1h");
...
If my understanding of the documentation is correct, I should be able to use 1h
value, but I'm getting me the following exception:
DateTimeParseException: Text cannot be parsed to a Duration
I retrieve the 1h
value from some configuration, for the sake of simplicity I've omitted the other code.
How can I fix this?
CodePudding user response:
You are not using correct format, use below -
Duration d = Duration.parse("PT1H");
CodePudding user response:
According to the documentation:
The string starts with an optional sign, denoted by the ASCII negative or positive symbol. If negative, the whole period is negated. The ASCII letter
"P"
is next in upper or lower case. 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. The ASCII letter"T"
must occur before the first occurrence, if any, of an hour, minute or second section. At least one of the four sections must be present ...
It is mandatory for the string you are parsing to start with "PT"
either in upper case or in lower case.
Letter "H"
in hour section also can be either in upper case or in lower case.
System.out.println(Duration.parse("pt1h"));
Output:
PT1H