CSV文件日期解析失败求助:DateTimeParseException异常
解决Java解析"23/FEB/23"日期的问题
问题根源
报错的核心原因是月份缩写的解析依赖Locale环境,如果Java默认Locale不是英文,DateTimeFormatter无法识别大写的"FEB"英文月份缩写。另外需确保格式字符串与实际日期格式完全匹配(此处应为dd/MMM/yy)。
修复代码
// 指定英文Locale,确保能识别英文月份缩写 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MMM/yy", Locale.ENGLISH); String exp = record.get("expiry"); LocalDate expiry = null; if (exp != null && !exp.isEmpty()) { expiry = LocalDate.parse(exp, dateTimeFormatter); }
额外优化建议
- 若日期月份缩写存在大小写混合(如Feb/feb),可添加宽松解析模式提升兼容性:
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MMM/yy", Locale.ENGLISH) .withResolverStyle(ResolverStyle.LENIENT); - 读取后先对日期字符串做去空格处理,避免隐藏空白字符导致解析失败:
exp = exp.trim();
内容的提问来源于stack exchange,提问作者spa
相关产品推荐
相关产品推荐

