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

KMM中获取当前UTC时间异常:返回1970年1月1日及0值求助

在KMM中获取当前UTC时间的正确方式

你遇到的DateTime.now().utc.milliseconds返回1970年 epoch 初始时间的问题,大概率是因为使用的日期库或调用方式不正确。下面是官方推荐的解决方案:

步骤1:引入适配KMM的日期时间库

确保项目中添加了kotlinx-datetime(Kotlin官方推出的跨平台日期时间库),在build.gradle.kts的commonMain依赖块中添加:

implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.4.1") // 可替换为最新版本

步骤2:正确获取UTC时间

获取UTC时间戳(毫秒)

import kotlinx.datetime.Clock

val currentUtcMillis = Clock.System.now().toEpochMilliseconds()

获取UTC日期时间对象

如果需要具体的年、月、日等字段,可以转换为带UTC时区的DateTime对象:

import kotlinx.datetime.Clock
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime

val currentUtcDateTime = Clock.System.now().toLocalDateTime(TimeZone.UTC)
// 可直接访问currentUtcDateTime.year、month、dayOfMonth等属性

问题原因说明

你之前的代码返回 epoch 初始时间,通常是因为调用的DateTime.now()没有正确绑定系统时钟,或者使用的库未适配KMM的跨平台环境。而kotlinx-datetime的Clock.System.now()是专门为多平台设计的,会正确读取当前系统的UTC时间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:50:28