Java date vs Gregorian calendar / 48 hours difference?

I had a curious situation at work, where the application sent us XML containing the value "0001-01-01", which was parsed into an instance XmlGregorianCalendar. Then I realized that the value magically converted to "0001-01-03" was added the exact amount of 2 days.

This happened during the conversion from GregorianCalendarto Date, which I reproduced as follows:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class Test {

    public static void main(String[] args) throws ParseException, DatatypeConfigurationException {
        final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        GregorianCalendar gregCalendar = new GregorianCalendar();
        gregCalendar.setTime(dateFormat.parse("0001-01-01"));
        XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregCalendar);

        System.out.println("calendar: " + calendar);
        System.out.println("date: " + calendar.toGregorianCalendar().getTime());
    }
}

Output Example:

calendar: 0001-01-01T00: 00: 00.000Z
date: Monday 03 January 00:00:00 GMT 1

Milliseconds differ in the exact amount of 172800000. Does anyone know why?

+4
source share

Source: https://habr.com/ru/post/1684242/


All Articles