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

Kotlin中基于UTC时区实现moment.js的fromNow功能问题排查

解决基于UTC时间复刻moment.fromNow的问题

问题核心是你的代码中,PrettyTime默认使用设备本地时区进行时间计算,导致设备时间与UTC时间不一致时,出现时间差方向和数值错误。比如你提到的场景:设备本地时间9:44,当前UTC时间15:19,输入UTC时间11:48,PrettyTime用本地时间9:44对比11:48,误判为“2 hours from now”,而正确的UTC时间差应为15:19-11:48≈3小时前。

修改方案

通过强制PrettyTime使用UTC时区完成所有计算,确保和moment.fromNow的UTC基准逻辑对齐:

import org.ocpsoft.prettytime.PrettyTime
import java.time.Instant
import java.time.format.DateTimeParseException
import java.util.*

fun formatDuration(dateTime: String): String {
    try {
        val parsedUtcInstant = Instant.parse(dateTime)
        val utcTimeZone = TimeZone.getTimeZone("UTC")
        
        // 初始化使用UTC时区的PrettyTime实例
        val prettyTime = PrettyTime(Locale.getDefault(), utcTimeZone)
        // 设置基准时间为当前UTC时间
        prettyTime.reference = Date.from(Instant.now())
        
        return prettyTime.format(Date.from(parsedUtcInstant))
    } catch (e: DateTimeParseException) {
        e.printStackTrace()
        return "Invalid date/time format"
    }
}

关键修改说明

  • 显式指定PrettyTime的时区为UTC,彻底避免本地时区干扰
  • 基准时间reference直接使用Instant.now()(本身就是UTC时间)转换的Date,无需多余的时区转换操作
  • 待格式化的时间保持为UTC标准的Instant,转换为Date后传入PrettyTime,确保计算全程基于UTC

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:36:59