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

Kotlin中时间戳转换返回错误日期的原因排查

问题原因及解决方案

核心原因:时间戳单位不匹配

你代码中使用的1708395041是秒级时间戳,但Kotlin/Java里的Date(long)构造器、Calendar.timeInMillis属性要求的是毫秒级时间戳(1秒=1000毫秒)。

直接传入秒级时间戳会导致系统把这个值当成毫秒解析,相当于把实际时间往前大幅偏移,最终得到错误的「Jan 20, 01:14 PM」。

修正方法

将时间戳乘以1000转换为毫秒级:

val timestamp = 1708395041L * 1000
val fullDateFormat = SimpleDateFormat("MMM dd, hh:mm a", Locale.getDefault())
Log.d("t", "date ${fullDateFormat.format(Date(timestamp))}")

修正后就能得到和查询结果一致的「Feb 20, 02:10 PM」(需保证设备时区与查询工具一致)。

额外建议

避免使用过时的SimpleDateFormat和Calendar类(它们线程不安全,API设计不够直观),推荐使用Java 8+的java.time标准库(Kotlin原生支持):

import java.time.*
import java.time.format.DateTimeFormatter

val timestampSeconds = 1708395041L
val formatter = DateTimeFormatter.ofPattern("MMM dd, hh:mm a", Locale.getDefault())
val dateTime = Instant.ofEpochSecond(timestampSeconds)
    .atZone(ZoneId.systemDefault())
    .toLocalDateTime()
Log.d("t", "date ${formatter.format(dateTime)}")

这个API直接支持秒级时间戳(Instant.ofEpochSecond),无需手动转毫秒,代码更清晰可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 08:12:43