首页 > 解决方案 > 字符串月-年到本地日期

问题描述

我正在尝试将一些日期字符串解析为日期值,但是,使用下面的代码,我遇到了一个异常:

我的代码

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

你能帮我解决一下吗?

标签: javadatejava-8

解决方案


    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

你的代码出了什么问题?

您的代码有两个问题:

  1. 格式模式字符串区分大小写。大写YYYY是基于周的年份,仅对周数有用。使用小写yyyyuuuu.
  2. 月和年没有定义日期,因此您不能轻易地将它们解析为LocalDate. 我建议你解析成aYearMonth然后转换。在转换中,您需要决定一个月中的哪一天。另一种方法是通过DateTimeFormatterBuilder.parseDefaulting().

链接

相关问题:


推荐阅读