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

Android中SimpleDateFormat美区转瑞典时区:模拟器正常三星真机异常

问题描述
  • 场景:Android平台使用SimpleDateFormat将美国区域时间格式转换为瑞典区域格式
  • 异常现象:模拟器转换正常(输入06:45 AM输出06:45 FM),三星真机输出仍为06:45 AM,其他设备/系统版本无问题
  • 范围:仅时间的AM/PM转换异常,日期转换在模拟器和真机上均正常
问题代码
SimpleDateFormat inputFormat = new SimpleDateFormat("hh:mm a", Locale.US);
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a", new Locale("sv"));
try {
    return outputFormat.format(inputFormat.parse(date));
} catch (ParseException e) {e.printStackTrace();}
return null;
解决方案

1. 指定完整Locale(语言+国家)

三星设备可能对仅指定语言代码的Locale处理存在兼容问题,尝试使用包含国家代码的Locale实例,确保加载正确的瑞典本地化资源:

// 明确指定瑞典(瑞典)的Locale
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a", new Locale("sv", "SE"));

2. 替换为Java 8+的DateTimeFormatter(推荐)

SimpleDateFormat是线程不安全的旧API,且厂商定制化容易引发兼容问题。推荐使用Android 7.0(API 24)以上原生支持的DateTimeFormatter,低版本可通过Desugar工具兼容:

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

// 输入格式化器(美国区域)
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.US);
// 输出格式化器(瑞典区域)
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("hh:mm a", new Locale("sv", "SE"));

try {
    LocalTime time = LocalTime.parse(date, inputFormatter);
    return time.format(outputFormatter);
} catch (Exception e) {
    e.printStackTrace();
    return null;
}

3. 手动映射AM/PM标识(兜底方案)

如果上述方法仍无效,可直接手动处理AM/PM的转换逻辑,避免依赖系统本地化资源:

SimpleDateFormat inputFormat = new SimpleDateFormat("hh:mm a", Locale.US);
try {
    Date parsedDate = inputFormat.parse(date);
    Calendar cal = Calendar.getInstance();
    cal.setTime(parsedDate);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    // 提取纯时间字符串
    String timeStr = new SimpleDateFormat("hh:mm", Locale.US).format(parsedDate);
    // 手动替换为瑞典语的上午/下午标识
    return timeStr + (hour < 12 ? " FM" : " EM");
} catch (ParseException e) {
    e.printStackTrace();
    return null;
}
原因分析

三星部分设备的系统对Locale资源加载做了定制化处理:仅指定语言代码sv时,系统可能未正确加载瑞典语的AM/PM本地化字符串,而是 fallback 到了默认的英文标识;或者系统内置的瑞典语区域格式被修改,导致SimpleDateFormat无法获取正确的本地化映射。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:20:38