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

无法用YYYYMMDDhhmmss格式将字符串转为LocalDateTime(JDK17,禁用yyyy/dd)

DateTimeParseException 异常修复方案

问题根源:格式符完全用错了

你的解析失败是因为使用了错误的日期格式符,和JDK版本无关:

  • YYYY 是基于周的年份,不是普通公历年,和输入的2012(公历年)不匹配
  • DD 是一年中的第N天,不是当月的日期,输入的23是8月23号,不是年中第23天,解析必然失败
  • hh 是12小时制小时,输入的15是24小时制,必须用HH

修正后的代码

import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;

public class DateTimeParseFix {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime date = LocalDateTime.parse("20120823151034", formatter);
        System.out.println(date); // 输出:2012-08-23T15:10:34
    }
}

关于你提到的「无法采用yyyy和dd方案」

你的输入字符串是标准的「公历年-月-日-24小时制时分秒」结构,yyyy(公历年)和dd(当月日期)是唯一匹配的格式符,不存在替代方案——之前的报错完全是格式符误用导致的,和JDK版本无关。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:32:10