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
相关产品推荐
相关产品推荐

