gpt4 book ai didi

java - JSR310 Year.parse()抛出DateTimeParseException,其值小于1000

转载 作者:行者123 更新时间:2023-12-01 11:47:39 25 4
gpt4 key购买 nike

我正在尝试使用java.time.Year.parse()解析从0到1000的Year String值,但是使用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)
[...]

我究竟做错了什么?

最佳答案

需要填充到4位数字

Year.parse(String.format("%04d", i));

Parsing year: 2000
Parsing year: ....
Parsing year: 4
Parsing year: 3
Parsing year: 2
Parsing year: 1
Parsing year: 0

如果您想在第0年之前解析,则可以使用
Year.parse("-0001");

关于java - JSR310 Year.parse()抛出DateTimeParseException,其值小于1000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61907458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com