简体   繁体   English

GregorianCalendar,自纪元以来时间不稳定

[英]GregorianCalendar with erratic time since epoch

I'm converting times to/from an external system that uses 2000.01.01 as its epoch. 我正在将时间转换为使用2000.01.01作为其时代的外部系统。 I require milliseconds since epoch for various calculations, so I convert between the two by using a constant (ignoring the nuances of leap seconds etc etc; my constant might not be exact, but that doesn't matter for now). 因为各种计算的纪元,我需要几毫秒,所以我通过使用常量(忽略闰秒的细微差别等等)在两者之间转换;我的常数可能不准确,但现在无关紧要)。 Whilst testing I noticed an oddity of time conversions. 测试时,我发现时间转换很奇怪。

Calendar epoch = new GregorianCalendar(TimeZone.getTimeZone("Zulu"));
epoch.set(2000,Calendar.JANUARY,1,0,0,0);
System.out.println("EPOCH DIFF:"+(epoch.getTime().getTime()-946684800000L));

You'd think this would always give the same result. 你认为这总会给出相同的结果。 And it does if you run it in a loop: 如果你在一个循环中运行它会这样做:

for(int i = 0; i < 10; i++) {
        System.out.println("EPOCH DIFF:"+(epoch.getTime().getTime()-946684800000L));
    }

(RESULT: -400)

However if you run in a new VM again and again the value keeps changing (seemingly) randomly! 但是,如果您一次又一次地在新VM中运行,则值会随机变化(看似)! I just ran it 5 times in quick succession in different JVMs and get different results: 我只是在不同的JVM中连续运行了5次,得到了不同的结果:

-276
-612
-376
-458
-573

I've redone the test with different timezones and get the same issue. 我用不同的时区重做测试并得到同样的问题。

Does anyone have any idea what could be causing this? 有谁知道是什么原因引起的?

Calendar object time have precision till millisecond. 日历对象时间精确到毫秒。 In your set epoch.set(2000,Calendar.JANUARY,1,0,0,0) method, the milli second value won't be reset to 0. 在set epoch.set(2000,Calendar.JANUARY,1,0,0,0)方法中,毫秒秒值不会重置为0。

You can separately set the same to zero as follows to get identical difference across multiple runs 您可以按如下方式单独将其设置为零,以在多次运行中获得相同的差异

 epoch.set(Calendar.MILLISECOND, 0)

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

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