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

Java使用DateTimeFormatter解析日期字符串报错是什么原因?

问题原因

你遇到的解析错误是因为定义的DateTimeFormatter格式模板和输入的日期字符串不匹配,存在两处格式符使用错误:

  • EEEE 是星期全称格式符,对应 Wednesday 这类完整拼写,而你的输入是星期缩写 Wed,需要替换为缩写对应的格式符 E
  • hh 是12小时制的小时格式符,仅支持01-12的数值,你的输入是24小时制的00:00:00,需要替换为24小时制对应的格式符HH

修正后代码

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM d HH:mm:ss zzz yyyy", Locale.US);
String date = "Wed Nov 18 00:00:00 COT 2020";
LocalDateTime localDateTime = LocalDateTime.parse(date, formatter);
System.out.println(localDateTime);
System.out.println(formatter.format(localDateTime));

补充说明

你的输入字符串中包含时区信息COT,如果后续需要做跨时区的时间计算,建议先使用ZonedDateTime完成解析,再按需转换为LocalDateTime,避免时区偏移导致的时间错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:36:07