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

Android开发中Java日期字符串转Date抛ParseException问题求助

解决Java中日期字符串转Date的ParseException问题

嘿,这个问题我之前踩过坑!你的代码格式字符串写得没问题,问题出在**Locale(区域设置)**上。

默认情况下,SimpleDateFormat会使用设备的系统Locale,如果你的设备默认Locale不是英文,它就无法识别"Sun"、"May"这些英文的星期和月份缩写,所以才会抛出ParseException。

修正方案:指定英文Locale

创建SimpleDateFormat的时候,显式传入英文Locale(比如Locale.ENGLISH或Locale.US),这样就能正确解析英文格式的日期字符串了:

SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
try {
    Date date = formatter.parse("Sun May 20 18:07:13 EEST 2018");
    // 这里处理转换后的Date对象
} catch (ParseException e) {
    e.printStackTrace();
}

更推荐的方案:使用Java 8+新日期API

如果你项目支持Java 8及以上(Android API 26+,或者通过Desugar兼容低版本),强烈建议使用java.time包下的新日期时间API——因为SimpleDateFormat是线程不安全的,新API设计更严谨、功能更强大:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

// ...

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
ZonedDateTime zonedDateTime = ZonedDateTime.parse("Sun May 20 18:07:13 EEST 2018", formatter);

// 如果需要兼容旧代码转换成java.util.Date:
Date date = Date.from(zonedDateTime.toInstant());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:08:59