I am trying to convert from millisecond time stamp to XMLGregorianCalendar and back, but I seem to be getting wrong results. Am I doing something wrong? It seems I am gaining days.
// Time stamp 01-Jan-0001 00:00:00.000
Long ts = -62135740800000L;
System.out.println(ts);
System.out.println(new Date(ts)); // Sat Jan 01 00:00:00 PST 1 .. Cool!
// to Gregorian Calendar
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(ts);
// to XML Gregorian Calendar
XMLGregorianCalendar xc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
// back to GC
GregorianCalendar gc2 = xc.toGregorianCalendar();
// to Timestamp
Long newTs = gc2.getTimeInMillis();
System.out.println(newTs); // -62135568000000 .. uh?
System.out.println(new Date(newTs)); // Mon Jan 03 00:00:00 PST 1 .. where did the extra days come from?
Interesting – it works fine for values down to (about) -10000000000000L (and positive values) but larger negative values become inconsistent.
If you print out
gc,xc, andgc2, you can see where the problem arises (the conversion from XMLGregorianCalendar to GregorianCalendarIf you print out the fields of
xc, you get 1,1,1.For
gc2, you get 1,0,1 (which matchesxc, because months are zero-based in GregorianCalendar)However, adding these 3
printlncalls changes the output from printing outgc2! – thetime=?output fromgc2changes totime=-62135568000000– so some calculation has been triggered by querying theGregorianCalendarobject; theareFieldsSetproperty also changes fromfalsetotrue.The timezones of the two GregorianCalendars are different, but this does not account for the error, which persists even if you set explicit TimeZone and Locale.