java - 字符串月-年到本地日期
问题描述
我正在尝试将一些日期字符串解析为日期值,但是,使用下面的代码,我遇到了一个异常:
我的代码
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("MMMM-YYYY"))
.toFormatter(Locale.ENGLISH);
LocalDate KFilter = LocalDate.parse("August-2021", formatter);
错误日志是
java.time.format.DateTimeParseException: Text 'August-2021' could not be parsed:
Unable to obtain LocalDate from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2021, MonthOfYear=8},
ISO of type java.time.format.Parsed
你能帮我解决一下吗?
解决方案
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("MMMM-uuuu"))
.toFormatter(Locale.ENGLISH);
LocalDate kFilter = YearMonth.parse("August-2021", formatter).atDay(1);
System.out.println(kFilter);
输出:
2021-08-01
你的代码出了什么问题?
您的代码有两个问题:
- 格式模式字符串区分大小写。大写
YYYY
是基于周的年份,仅对周数有用。使用小写yyyy
或uuuu
. - 月和年没有定义日期,因此您不能轻易地将它们解析为
LocalDate
. 我建议你解析成aYearMonth
然后转换。在转换中,您需要决定一个月中的哪一天。另一种方法是通过DateTimeFormatterBuilder.parseDefaulting()
.
链接
相关问题:
推荐阅读
- jupyter - 如何在 JupyterHub 中设置默认 umask
- nativescript - Nativescript Sidekick 发布到 App Store
- algorithm - 组合向量加法最小化问题
- ruby - 轨道中的保存方法是强制性的吗?
- java - 获取String值的ArrayList的值
- c - for 循环正在初始化三个变量
- django - 使用 Django Rest Framework 搜索后如何获取查询集值
- android - Android:处理不同dip设备的文本大小
- react-native - React Native 应用程序在启动时崩溃 - 仅在某些 Android 和 IOS 设备上
- exception - Camel Spring DSL onException 根本不会触发