You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java转换MM/yyyy格式字符串为LocalDate抛出DateTimeParseException如何解决

异常触发原因

LocalDate 是用来表示包含「年、月、日」三个维度的完整日期类型,你使用的格式化/解析模式 MM/yyyy 仅包含年月两个维度的信息,缺失了必要的「天」字段,java.time 无法仅凭年月就推断出合法的天数值,因此抛出解析失败异常。

修复方案

可以根据业务需求选择对应方案:

  • 方案1:必须使用LocalDate类型的话,解析时手动配置默认天值
    可以通过DateTimeFormatterBuilder给解析器补全默认的天字段,比如默认取当月1号:

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("MM/yyyy")
        // 配置默认天为当月1号
        .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
        .toFormatter();
    String s= "06/2018";
    LocalDate localDate4 = LocalDate.parse(s,formatter);
    // 最终得到的结果为 2018-06-01
    
  • 方案2:改用适配年月维度的YearMonth类型接收
    如果业务本身只需要存储年月维度的数据,不需要具体的天,直接用java.time.YearMonth类型更合理,不需要额外补字段:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/yyyy");
    String s= "06/2018";
    YearMonth yearMonth = YearMonth.parse(s, formatter);
    
    // 后续如果需要转LocalDate,也可以灵活指定天
    LocalDate firstDay = yearMonth.atDay(1);
    LocalDate lastDay = yearMonth.atEndOfMonth();
    
  • 方案3:调整格式化规则,保留天维度信息
    如果允许修改日期转字符串的逻辑,直接把天也加入格式化模式里,后续解析就不会缺失字段:

    // 格式化时保留天的信息
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    String s= localDate1.format(formatter);
    // 此时字符串为 14/06/2018,直接解析不会报错
    LocalDate localDate4 = LocalDate.parse(s,formatter);
    

内容的提问来源于stack exchange,提问作者user739115

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:18:04