计算JVM与UTC的毫秒级时间差:夏令时适配问题及测试修正
计算JVM本地时刻与UTC的毫秒时差问题
我正为一个看似简单的问题困扰:想要计算JVM(运行代码的机器本地时刻)与UTC时刻之间的毫秒级时间差(偏移量)。我尝试了以下Kotlin代码:
// 1 val difference = TimeZone.getDefault().getOffset(System.currentTimeMillis())
// 2 val difference = ZoneId.systemDefault().rules.getOffset(Instant.EPOCH).totalSeconds * 1000
// 3 val difference = ZonedDateTime.now(ZoneId.systemDefault()).offset.totalSeconds * 1000
具体场景:2024年2月22日,我在位于美国西海岸的Mac上运行代码(处于夏令时期间),上述三种方法均返回-28800000(基于时区的结果),但我期望得到-25200000(夏令时敏感、基于时刻的结果)。请问我哪里出错了?我需要不依赖特定时区字符串、可在任意机器运行的方案。
编辑补充
@Louis Wasserman指出我的预期错误,当前实际时差确实为
-28800000。错误预期源于我的测试代码:
@Test fun timeStrToEpochMillis_invariantValidation_happyPaths() { // Arrange val testTimeStr = "2023-06-13 20:21:46" // Act val result = timeStrToEpochMillis(testTimeStr) // Assert assertEquals(1686687706000, result) }
对应函数:
fun timeStrToEpochMillis(timeStr: String): Long { val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") return df.parse(timeStr).time }
在默认时区为UTC的容器中运行该测试可通过,但在默认时区为太平洋时区的本地机器上会失败。我后来意识到应基于测试时间字符串计算时差来修正测试:
@Test fun timeStrToEpochMillis_invariantValidation_happyPaths() { // Arrange val testTimeStr = "2023-06-13 20:21:46" // Act val result = timeStrToEpochMillis(testTimeStr) val diff = TimeZone.getDefault().getOffset(result) // Assert assertEquals(1686687706000 + diff, result) }
再次感谢@Louis Wasserman指出问题。
内容的提问来源于stack exchange,提问作者youngrrrr
相关产品推荐
相关产品推荐

