简体   繁体   English

java.time.Duration中的错误

[英]Bug in java.time.Duration

I need to parse Durations from strings. 我需要从字符串中解析持续时间 Java 8 provide a method for that taking the ISO-8601 standard as a basis: Java 8提供了一种以ISO-8601标准为基础的方法:

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 . 由于标准规定“允许通过共同协议省略'T'字符”, 持续时间的一些Javadoc例子中没有留下T According to them, the following expression should parse as "-6 hours and +3 minutes": 据他们说,以下表达式应解析为“-6小时+3分钟”:

"P-6H3M"

But I found that all expressions ommitting the T throw a DateTimeParseException . 但是我发现所有表达式都省略了T抛出一个DateTimeParseException Is that a bug in the parse() method or am I missing something? 这是parse()方法中的错误还是我错过了什么?

In the JavaDoc of parse() : JavaDocparse()

The ASCII letter "T" must occur before the first occurrence, if any, of an hour , minute or second section. ASCII字母“T” 必须出现在第一次出现(如果有) 小时分钟节之前。

That means you have to include T whenever you use H , M , or S . 这意味着无论何时使用HMS ,都必须包含T


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: Duration.parse使用的正则表达式是:

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. 输入P-6H3M与此正则表达式不匹配。 If it is changed to 如果改为

"(T?(?:([-+]?[ ...

in the fourth line (note the ? after the T ), the examples match (test it on http://regexpal.com/ ). 在第四行(注意T之后的? ),示例匹配(在http://regexpal.com/上测试)。

So it looks like you have found an inconsistency between code and JavaDoc. 所以看起来你发现代码和JavaDoc之间存在不一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM