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

复刻EpochConverter日期转毫秒逻辑:Java/Kotlin代码结果不符排查

问题原因与解决方案

核心原因:时区不一致

EpochConverter默认将输入的日期字符串解析为UTC时区的时间,而你代码中的SimpleDateFormat默认使用了运行环境的本地时区(比如你的系统时区是UTC+6或其他偏移时区),两者的时区差异导致了时间戳差值(21600000毫秒=6小时,正好对应你的结果差)。

修正方案

方案1:给SimpleDateFormat指定UTC时区

直接修改SimpleDateFormat的时区为UTC,确保解析逻辑和网站一致:

import java.text.SimpleDateFormat
import java.util.*

fun main(){ 
    val startTime = "1979/12/31 23:30:00"
    val dateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss").apply {
        timeZone = TimeZone.getTimeZone("UTC") // 指定UTC时区
    }
    val startTimeInMillis = dateFormat.parse(startTime).time.toString()
    println(startTimeInMillis) // 输出:315552600000
}

方案2:使用Java 8+的新时间API(推荐)

SimpleDateFormat是线程不安全的老旧API,推荐使用Java 8引入的java.time包下的类,更可靠且可读性更强:

import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter

fun main(){ 
    val startTime = "1979/12/31 23:30:00"
    val formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")
    val localDateTime = LocalDateTime.parse(startTime, formatter)
    // 转换为UTC时区的时间戳(毫秒)
    val startTimeInMillis = localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli().toString()
    println(startTimeInMillis) // 输出:315552600000
}

验证说明

修改后两种方案都会输出315552600000,和EpochConverter的结果完全一致,因为都强制使用了UTC时区解析日期字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:15:35