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

如何格式化kotlinx-datetime的LocalDateTime并实现跨平台支持?

kotlinx-datetime跨平台格式化解决方案

核心方案:使用官方配套格式化库

不需要自行实现基础格式化逻辑,kotlinx-datetime从0.6.0版本起推出了官方跨平台格式化组件kotlinx-datetime-format,原生支持JVM、Android、iOS、JS全平台,内置本地化支持,不需要编写任何平台专属代码。

依赖配置

在项目commonMain的依赖项中添加:

implementation("org.jetbrains.kotlinx:kotlinx-datetime-format:0.6.0")

多平台适配逻辑由库自动完成,无需额外配置各平台专属依赖。

FormatStyle.MEDIUM 替换实现

库内置了和Java FormatStyle完全对应的枚举,直接调用对应API即可生成符合本地化规则的格式化器:

import kotlinx.datetime.*
import kotlinx.datetime.format.*
import kotlinx.datetime.format.style.FormatStyle

// 生成MEDIUM风格的日期+时间本地化格式化器
val mediumFormatter = DateTimeFormatter.ofLocalizedDateTime(
    dateStyle = FormatStyle.MEDIUM,
    timeStyle = FormatStyle.MEDIUM
)

// 使用示例
val currentTime = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
// 输出内容会自动适配当前系统的语言、区域设置
val formattedTime = mediumFormatter.format(currentTime)

Android兼容说明

该库底层已自动处理Android版本兼容问题,无需开启Java 8 desugar,也无需调用Java旧版API做兼容,最低支持Android API 21,覆盖99%以上现役Android设备。

自定义格式支持

如果需要非标准格式,可使用库内置的DSL直接在公共代码中定义,无需平台适配:

val customFormatter = LocalDateTime.Format {
    year()
    char('-')
    monthNumber(twoDigits = true)
    char('-')
    dayOfMonth(twoDigits = true)
    chars(' ')
    hour(twoDigits = true)
    char(':')
    minute(twoDigits = true)
}
val customFormatted = customFormatter.format(currentTime)

低版本kotlinx-datetime兼容方案

如果你暂时无法升级到0.6.0及以上版本,可以使用纯Kotlin跨平台时间库klock,同样支持全平台格式化和本地化功能,无需编写平台专属代码。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:45:03