有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java字符串MonthYear到本地日期

我试图将某个日期字符串解析为日期值,但是,使用以下代码,我得到一个异常:

我的代码

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

你能帮我解决这个问题吗


共 (1) 个答案

  1. # 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表示基于周的年份,仅对周数有用。使用小写yyyyuuuu
    2. 月份和年份没有定义日期,因此您无法轻松地将它们解析为LocalDate。我建议您解析为YearMonth,然后转换。在转换中,您需要在月份的某一天进行决策。另一种方法是通过DateTimeFormatterBuilder.parseDefaulting()指定月份的某一天

    链接

    相关问题: