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

SimpleDateFormat格式化日期时月份显示为M10的异常问题

问题原因
  • 该问题是Locale携带的历法配置与系统API变更共同导致的:Android 7.0(API 24)开始Resources.Configuration.locale方法已被废弃,返回的Locale可能丢失配置、或携带系统默认的非公历历法参数,当SimpleDateFormat使用非公历历法解析MMM格式符时,就会输出M+数字的格式而非预期的英文月份缩写。
  • 部分系统版本更新后会修改默认的Locale附加配置,就算此前运行正常,也可能在系统更新后触发该问题。
修复方案
  1. 替换废弃的Locale获取方法,同时强制为SimpleDateFormat指定公历历法,适配全版本系统:
Locale locale;
// 适配不同系统版本的Locale获取逻辑
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = context.getResources().getConfiguration().getLocales().get(0);
} else {
    locale = context.getResources().getConfiguration().locale;
}
dateFormatDayMonth = new SimpleDateFormat("EEE, MMM d", locale);
// 强制指定使用公历,排除历法配置对输出格式的影响
dateFormatDayMonth.setCalendar(new GregorianCalendar(locale));
textView.setText(dateFormatDayMonth.format(calendar.getTime()));
  1. 如果需求是固定输出英文格式的日期,不受系统Locale切换的影响,可以直接指定Locale为Locale.US,一行即可修复:
dateFormatDayMonth = new SimpleDateFormat("EEE, MMM d", Locale.US);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:36:02