【发布时间】:2020-09-06 11:40:44
【问题描述】:
我正在尝试使用 java.time.Year.parse() 解析 0 到 1000 范围内的年份字符串值,但是使用 java.time.format.DateTimeParseException: Text '999' could not be parsed at index 0 解析失败。
Year.parse 的 javadoc 声明:
Obtains an instance of Year from a text string such as 2007.
The string must represent a valid year. Years outside the range 0000 to 9999
must be prefixed by the plus or minus symbol.
重现此问题的示例测试:
@Test
public void parse_year() {
for (int i = 2000; i >= 0; i--) {
System.out.println("Parsing year: " + i);
Year.parse(String.valueOf(i));
}
}
当达到年份 999 时,测试抛出异常:
Parsing year: 1003
Parsing year: 1002
Parsing year: 1001
Parsing year: 1000
Parsing year: 999
java.time.format.DateTimeParseException: Text '999' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.Year.parse(Year.java:292)
at java.time.Year.parse(Year.java:277)
[...]
我做错了什么?
【问题讨论】: