简体   繁体   English

减去1ms会导致意外行为

[英]Subtraction of 1ms leads to unexpected behaviour

What is wrong? 怎么了? I assume that if I subtract 1ms from 1 Jan 1980 0:0:0 then I've got 1979. But I must subtract about 500+ ms for this. 我假设如果我从1980年1月1日0:0:0减去1毫秒,那么我得到1979。但是我必须为此减去500毫秒以上。 Please, give me a hint. 请给我一个提示。

val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
cal.set(1980, 0, 1, 0, 0, 0)
val date = new Date
date.setTime(cal.getTimeInMillis()) // <- 1980 Jan 01 0:0:0
date.setTime(cal.getTimeInMillis() - 1) // <- 1980 Jan 01 0:0:0 too !!!

Updated. 更新。

The solution is 解决方案是

val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
cal.setTimeInMillis(0)
cal.set(1980, 0, 1, 0, 0, 0)

With Calendar.set(year, month, day, hourOfDay, minute, second) no milliseconds are set. 使用Calendar.set(year, month, day, hourOfDay, minute, second)不会设置毫秒。 Consequently the Calendar implementation sets the milliseconds to "unknown" which is actually treated as the midpoint within the given second. 因此,Calendar实现将毫秒设置为“未知”,这实际上被视为给定秒数内的中点。

Subtracting 500ms means you just step over the midpoint. 减去500毫秒意味着您只需跨过中点。 Same should happen if you add 500ms, which should bring you just over the second. 如果您增加500ms,也会发生同样的情况,这会使您略胜一秒。 Actually subtracting 500ms works and you must add 620ms to see the next second. 实际上减去500毫秒是可行的,您必须加620毫秒才能看到下一秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM