使用Java8将一年String解析为LocalDate [英] Parsing a year String to a LocalDate with Java8

查看:389
本文介绍了使用Java8将一年String解析为LocalDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Joda库,你可以做到

With Joda library, you can do

DateTimeFormat.forPattern("yyyy").parseLocalDate("2008")

在2008年1月1日创建LocalDate

that creates a LocalDate at Jan 1st, 2008

使用Java8,你可以尝试

With Java8, you can try to do

LocalDate.parse("2008",DateTimeFormatter.ofPattern("yyyy"))

但无法解析:

Text '2008' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2008},ISO of type java.time.format.Parsed

有没有其他选择,而不是专门写等......

Is there any alternative, instead of specifically writing sth like

LocalDate.ofYearDay(Integer.valueOf("2008"), 1)

推荐答案

LocalDate 解析要求所有的年,月和日期已被指定。

LocalDate parsing requires that all of the year, month and day are specfied.

您可以使用 DateTimeF指定月份和日期的默认值ormatterBuilder 并使用 parseDefaulting 方法:

You can specify default values for the month and day by using a DateTimeFormatterBuilder and using the parseDefaulting methods:

DateTimeFormatter format = new DateTimeFormatterBuilder()
     .appendPattern("yyyy")
     .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
     .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
     .toFormatter();

LocalDate.parse("2008", format);

这篇关于使用Java8将一年String解析为LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆