使用SimpleDateFormat解析日期字符串抛出ParseException异常求助
解决日期解析的ParseException问题
Hey there, let's break down why your date parsing is throwing that ParseException and fix it step by step.
核心问题:Locale不匹配
你当前使用的是Locale.GERMANY,但你的日期字符串里的星期缩写是英文的Mon(对应德语缩写是Mo),月份缩写也是英文的May(对应德语缩写是Mai)。SimpleDateFormat会严格按照指定的Locale来识别日期组件的语言规则,用德语的匹配逻辑去解析英文的日期文本,自然就会触发解析失败的异常。
快速修复方案(基于SimpleDateFormat)
只需要把Locale改成英文相关的即可,比如Locale.ENGLISH或者Locale.US,修改后的代码如下:
String time = "Mon May 07 00:31:29 GMT+02:00 2018"; Date parsedDate = new SimpleDateFormat("E MMM dd HH:mm:ss zXXX yyyy", Locale.ENGLISH).parse(time);
这样就能正确识别英文的日期组件,完成解析。
更推荐的方案:使用Java 8+的java.time API
SimpleDateFormat存在线程不安全的问题,而且API设计老旧容易踩坑。Java 8及以上版本提供的java.time包是更优的选择,代码逻辑更清晰,且天然支持线程安全。对应的实现代码如下:
import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.util.Date; public class DateParseFix { public static void main(String[] args) { String time = "Mon May 07 00:31:29 GMT+02:00 2018"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss zXXX yyyy", Locale.ENGLISH); ZonedDateTime zonedDateTime = ZonedDateTime.parse(time, formatter); // 如果需要兼容旧代码转换成java.util.Date Date parsedDate = Date.from(zonedDateTime.toInstant()); } }
这个方案不仅解决了当前的解析问题,还能避免SimpleDateFormat带来的潜在风险。
内容的提问来源于stack exchange,提问作者F.M.F.
相关产品推荐
相关产品推荐

