【问题标题】:String Month-Year to Local Date字符串月-年到本地日期
【发布时间】:2021-10-13 07:15:06
【问题描述】:

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

我的代码

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

你能帮我解决一下吗?

【问题讨论】:

标签: java date java-8


【解决方案1】:
    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 用于基于周的年份,仅适用于周数。使用小写 yyyy 或 uuuu。
  2. 月份和年份没有定义日期,因此您不能轻易地将它们解析为LocalDate。我建议你解析成YearMonth 然后转换。在转换中,您需要决定一个月中的哪一天。另一种方法是通过DateTimeFormatterBuilder.parseDefaulting() 指定月份中的某一天。

链接

相关问题:

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2020-08-26
    • 2020-12-19
    相关资源
    最近更新 更多