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

Java DateTimeFormatter解析dd-MMM-yyyy格式日期报错求助

问题:解析dd-MMM-yyyy格式日期时抛出DateTimeParseException

需要处理制表符分隔文件中的日期,格式为dd-MMM-yyyy(如1-Aug-2018或15-Sep-2023),编写的代码如下:

private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("d-MMM-uuuu");
private LocalDateTime toDate(String raw) {
       LocalDateTime date = LocalDateTime.parse(raw, DATE_FORMATTER);
    return date;
}

运行时抛出异常:

Exception in thread "main" java.time.format.DateTimeParseException: Text '1-Aug-2018' could not be parsed at index 2

已做排查操作:

  • 查阅Oracle Java官方文档
  • 尝试将模式中的d替换为dd,报错索引变为0
  • 尝试将uuuu替换为yyyy(确认问题不在此)
  • 搜索到的DateTimeFormatter示例多为格式化输出,而非解析输入
  • 在StackOverflow搜索到的多为过时方案,且示例模式与当前场景不符

解决建议
  1. 指定英文Locale(核心修复)
    MMM对应月份英文缩写,默认Locale若不是英文环境,会无法识别Aug、Sep这类缩写,这是解析失败的根本原因。创建DateTimeFormatter时需显式指定英文Locale:
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("d-MMM-uuuu", Locale.US);
  1. 匹配正确的日期类型
    输入字符串仅包含日期信息(无时分秒),使用LocalDate解析更贴合数据结构,若确实需要LocalDateTime,可后续转换为当日起始时间:
private LocalDateTime toDate(String raw) {
    LocalDate date = LocalDate.parse(raw, DATE_FORMATTER);
    return date.atStartOfDay(); // 转换为当日0点的LocalDateTime
}
  1. 保留原日期模式
    d可以匹配1位或2位的日期值(如1或15),完全适配输入格式,无需修改为dd。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:02:13