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

使用SimpleDateFormat转字符串为时间:Eclipse正常Android Studio出错

解决SimpleDateFormat跨环境格式转换错误的问题

嘿,我看你碰到了个挺闹心的问题——同样的日期转换代码在Eclipse里跑起来好好的,到Android Studio就输出错误结果了!别着急,咱们来揪出问题根源。

问题核心:格式符用错了!

你代码里写的HH:MM AA里,MM其实是月份的格式符(对应01-12),而你要解析的是分钟,正确的格式符应该是mm(对应00-59)!

为什么Eclipse里看起来正常?大概率是Eclipse使用的JDK对SimpleDateFormat的容错性更高,悄悄帮你修正了这个错误;但Android的SimpleDateFormat实现严格遵循了Java的格式规则,所以直接输出了错误的结果。

修正后的代码示例

把格式符里的MM改成mm,同时记得指定Locale(避免系统区域设置影响AM/PM的解析):

SimpleDateFormat inputFormat = new SimpleDateFormat("HH:mm aa", Locale.ENGLISH);
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm", Locale.ENGLISH);

try {
    Date date = inputFormat.parse("03:45 PM");
    String convertedTime = outputFormat.format(date);
    Log.d("TimeConversion", convertedTime); // 正确输出15:45
} catch (ParseException e) {
    e.printStackTrace();
}

额外推荐:使用更可靠的日期API

SimpleDateFormat是线程不安全的,在Android中更推荐使用java.time系列API(Android 8.0及以上原生支持,低版本可以引入ThreeTenABP库),代码更简洁也更稳定:

// Android 8.0+ 写法
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("HH:mm aa", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);

LocalTime time = LocalTime.parse("03:45 PM", inputFormatter);
String convertedTime = time.format(outputFormatter);
Log.d("TimeConversion", convertedTime); // 输出15:45

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:21:36