I need to parse Durations from strings. Java 8 provide a method for that taking the ISO-8601 standard as a basis:
Duration.parse("p10d"); // parses as ten days
Duration.parse("pt1h"); // parses as one hour
As the standard states that "it is permitted to omit the 'T' character by mutual agreement" some of the Javadoc examples of Durations.parse() leave out the T
. According to them, the following expression should parse as "-6 hours and +3 minutes":
"P-6H3M"
But I found that all expressions ommitting the T
throw a DateTimeParseException
. Is that a bug in the parse()
method or am I missing something?
In the JavaDoc of parse()
:
The ASCII letter "T" must occur before the first occurrence, if any, of an hour , minute or second section.
That means you have to include T
whenever you use H
, M
, or S
.
The examples are wrong though:
"P-6H3M" -- parses as "-6 hours and +3 minutes"
"-P6H3M" -- parses as "-6 hours and -3 minutes"
"-P-6H+3M" -- parses as "+6 hours and -3 minutes"
The regular expression used by Duration.parse
is:
private static final Pattern PATTERN =
Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)D)?" +
"(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?",
Pattern.CASE_INSENSITIVE);
The input P-6H3M
is not matched by this regular expression. If it is changed to
"(T?(?:([-+]?[ ...
in the fourth line (note the ?
after the T
), the examples match (test it on http://regexpal.com/ ).
So it looks like you have found an inconsistency between code and JavaDoc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.