使用LocalDate解析自定义格式的字符串

自从JDK8推出新的日期处理类之后,就不推荐使用原来SimpleDateFormat来格式化日期了,可是在使用LocalDate去解析日期字符串时,感觉有那么一点点局限性,应该如何优雅的处理呢?

需求,格式化年月yyyy-MM

LocalDate parse = LocalDate.parse("2022-09", DateTimeFormatter.ofPattern("yyyy-MM"));

抛出异常如下:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2022-09' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=9, Year=2022},ISO of type java.time.format.Parsed
	at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
	at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
	at java.time.LocalDate.parse(LocalDate.java:400)
	at com.etoak.test.Test.main(Test.java:24)
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=9, Year=2022},ISO of type java.time.format.Parsed
	at java.time.LocalDate.from(LocalDate.java:368)
	at java.time.format.Parsed.query(Parsed.java:226)
	at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
	... 2 more

解决方案一,使用YearMonth

YearMonth parse = YearMonth.parse("2022-09", DateTimeFormatter.ofPattern("yyyy-MM"));

解决方案二,使用DateTimeFormatterBuilder

DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("yyyy-MM").parseDefaulting(ChronoField.DAY_OF_MONTH, 1).toFormatter();
LocalDate parse = LocalDate.parse("2022-09", formatter);

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wsdhla

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值