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搜索到的多为过时方案,且示例模式与当前场景不符
解决建议
- 指定英文Locale(核心修复)
MMM对应月份英文缩写,默认Locale若不是英文环境,会无法识别Aug、Sep这类缩写,这是解析失败的根本原因。创建DateTimeFormatter时需显式指定英文Locale:
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("d-MMM-uuuu", Locale.US);
- 匹配正确的日期类型
输入字符串仅包含日期信息(无时分秒),使用LocalDate解析更贴合数据结构,若确实需要LocalDateTime,可后续转换为当日起始时间:
private LocalDateTime toDate(String raw) { LocalDate date = LocalDate.parse(raw, DATE_FORMATTER); return date.atStartOfDay(); // 转换为当日0点的LocalDateTime }
- 保留原日期模式
d可以匹配1位或2位的日期值(如1或15),完全适配输入格式,无需修改为dd。
内容的提问来源于stack exchange,提问作者Terrible Tadpole
相关产品推荐
相关产品推荐

