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

如何使SimpleDateFormat输出AM/PM而非a.m./p.m.?

解决SimpleDateFormat显示a.m.而非AM的问题

问题出在**Locale(区域设置)**上:SimpleDateFormat的a格式符输出的AM/PM样式完全由当前使用的Locale决定。你的默认Locale可能采用了带点的格式(比如部分地区的英语变体),所以才会输出a.m.而非AM。

解决方案1:指定Locale.US

直接在创建SimpleDateFormat时传入Locale.US,就能强制输出无点的大写AM/PM格式:

val timeFormat = SimpleDateFormat("hh:mm:ss a", Locale.US)
val timeString = timeFormat.format(Date(transaction.time))

解决方案2:使用DateTimeFormatter(推荐API 24+)

SimpleDateFormat存在线程不安全的问题,Android API 24及以上更推荐使用java.time包下的DateTimeFormatter,同样通过指定Locale来控制格式:

import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale

val formatter = DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.US)
val timeString = Instant.ofEpochMilli(transaction.time)
    .atZone(ZoneId.systemDefault())
    .format(formatter)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:24:28