如何使用Java 8时间API将两位数年份转换为全年

我希望从我的项目中删除Joda-Time库.

我想把两位数转换成全年. Joda-Time的以下代码可以实现此目的.以下是joda-time的以下代码

DateTimeFormatter TWO_YEAR_FORMATTER = DateTimeFormat.forPattern("yy");
int year = LocalDate.parse("99"",TWO_YEAR_FORMATTER).getYear();
System.out.println(year);

产出:1999年

这是我期望的输出,这在我的情况下是有意义的.但是,当我使用java.time API尝试相同的过程时,它会生成DatetimeParseException.以下是java.time API的以下代码

DateTimeFormatter TWO_YEAR_FORMATTER = DateTimeFormatter.ofPattern("yy");
int year = LocalDate.parse("99",TWO_YEAR_FORMATTER).getYear();
System.out.println(year);

堆栈跟踪:

Exception in thread "main" java.time.format.DateTimeParseException: Text '99' Could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2099},ISO of type java.time.format.Parsed
    at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
    at java.base/java.time.LocalDate.parse(LocalDate.java:428)
    at scratch.main(scratch.java:10)
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {Year=2099},ISO of type java.time.format.Parsed
    at java.base/java.time.LocalDate.from(LocalDate.java:396)
    at java.base/java.time.format.Parsed.query(Parsed.java:235)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    ... 2 more

我没能看到堆栈跟踪的原因.如果有人可以帮助我理解以下场景并且还解释如何使用Java 8时间API将两位数年份转换为全年,那将是很好的.

解决方法

问题是你无法将一年自己解析为LocalDate. LocalDate需要更多信息.

您可以使用格式化程序的解析方法,它将为您提供TemporalAccessor,然后从中获取年份字段:

int year = TWO_YEAR_FORMATTER.parse("99").get(ChronoField.YEAR);
System.out.println(year);

解决两者之间的差异:这是两个不同的API.是的,它们非常相似,并且java.time软件包是通过JodaTime的设计决策获知的,但它从来没有打算成为它的替代品.

如果您想更改枢轴年份,请参阅this answer(认情况下,’99’将解析为2099而不是1999年).

相关文章

应用场景 C端用户提交工单、工单创建完成之后、会发布一条工...
线程类,设置有一个公共资源 package cn.org.chris.concurre...
Java中的数字(带有0前缀和字符串)
在Java 9中使用JLink的目的是什么?
Java Stream API Filter(过滤器)
在Java中找到正数和负数数组元素的数量