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

Android中如何按特定Locale格式化HH:mm时间(如12h05、12u05)

基于Locale自动格式化HH:mm时间(无需手动判断Locale)

问题描述

需要将HH:mm格式的时间字符串按当前Locale格式化,例如:

  • 12:05 在法语(FR)Locale下显示为 12h05
  • 12:05 在荷兰语(NL)Locale下显示为 12u05

目前通过手动判断Locale指定格式字符串的方式实现,希望找到无需手动判断、基于Locale的现成格式化方案。

现有实现代码

无效尝试(固定格式未适配Locale)

fun String.hourFormat() : String {
    // 原代码使用ISO_DATE_TIME错误,纯时间应使用ISO_LOCAL_TIME
    val time = LocalTime.parse(this, DateTimeFormatter.ISO_LOCAL_TIME)
    val formatter = DateTimeFormatter.ofPattern("HH:mm").withLocale(LocaleManager.currentLocale())
    return time.format(formatter)
}

手动判断Locale的实现

fun String.hourFormat() : String {
    val time = LocalTime.parse(this, DateTimeFormatter.ISO_LOCAL_TIME)
    val localePattern = when (LocaleManager.currentLocale().language) {
        "fr" -> "HH'h'mm"
        "nl" -> "HH'u'mm"
        else -> "HH:mm" // 默认 fallback
    }
    val formatter = DateTimeFormatter.ofPattern(localePattern)
    return time.format(formatter)
}

解决方案

方式1:Locale-分隔符映射表(推荐,易扩展)

无需硬编码when判断,通过维护Locale到自定义分隔符的映射表实现自动适配,新增Locale只需扩展映射表:

// 全局维护Locale与小时分隔符的映射
private val localeHourSeparatorMap = mapOf(
    Locale.FRENCH to "h",
    Locale("nl") to "u"
)

fun String.hourFormat(): String {
    val time = LocalTime.parse(this, DateTimeFormatter.ISO_LOCAL_TIME)
    val currentLocale = LocaleManager.currentLocale()
    // 获取对应分隔符,默认使用冒号
    val separator = localeHourSeparatorMap[currentLocale] ?: ":"
    val pattern = "HH'%s'mm".format(separator)
    val formatter = DateTimeFormatter.ofPattern(pattern)
    return time.format(formatter)
}

方式2:本地化预定义格式(需验证适配性)

部分Locale的系统预定义时间格式已符合需求,可通过DateTimeFormatterBuilder强制24小时制后使用:

fun String.hourFormat(): String {
    val time = LocalTime.parse(this, DateTimeFormatter.ISO_LOCAL_TIME)
    val currentLocale = LocaleManager.currentLocale()
    // 构建强制24小时制的本地化时间格式化器
    val formatter = DateTimeFormatterBuilder()
        .appendLocalized(null, FormatStyle.SHORT)
        .parseDefaulting(ChronoField.AMPM_OF_DAY, 0) // 强制使用24小时制
        .toFormatter(currentLocale)
    return time.format(formatter)
}

注意:这种方式需提前测试目标Locale的默认格式是否匹配需求,比如法语Locale的SHORT格式可能默认返回12:05而非12h05,不匹配时仍需使用方式1。

补充说明

  • 原代码中使用DateTimeFormatter.ISO_DATE_TIME解析纯时间字符串是错误的,应替换为DateTimeFormatter.ISO_LOCAL_TIME。
  • 映射表方式比when判断更易维护,后续新增Locale只需添加映射条目即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 16:40:14