Question

I'm converting times to/from an external system that uses 2000.01.01 as its epoch. 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! I just ran it 5 times in quick succession in different JVMs and get different results:

-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?

Was it helpful?

Solution

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.

You can separately set the same to zero as follows to get identical difference across multiple runs

 epoch.set(Calendar.MILLISECOND, 0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top