-4

I am struggling with the below date convert.

Original Date: Jan 2 0001 18:00 PM GMT-5:00.

Expected Date: Jan 3 0001 7:00 AM GMT+8:00.
Actual Date: Jan 5 0001 7:00 AM GMT+8:00.

    public static void main(String[] args) {
    XMLGregorianCalendar xmlC;
    try {
        xmlC = DatatypeFactory.newInstance().newXMLGregorianCalendar();
        xmlC.setYear(1);
        xmlC.setMonth(1);
        xmlC.setDay(2); // It is Jan 2!!
        xmlC.setHour(18);
        xmlC.setMinute(0);
        xmlC.setSecond(0);
        xmlC.setMillisecond(0);
        xmlC.setTimezone(-300);
        GregorianCalendar gC = xmlC.toGregorianCalendar();
        System.out.println(gC.getTime()); // Actual output: Wed Jan 05 07:00:00 CST 1
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }
}

May you please help me on this? Thank you in advance.

2

2 Answers 2

5
+25

As explained in this answer, your calendar is being shifted because you have specified your year as 1, meaning that this falls out of the GregorianCalendar and into the Julian Calendar, which XMLGregorianCalendar does not support.

Simply use xmlC.setYear(2016); to fix this.

0

try this into your code

XMLGregorianCalendar xmlC;
Calendar cal=Calendar.getInstance();
try {
    xmlC = DatatypeFactory.newInstance().newXMLGregorianCalendar();
    xmlC.setYear(cal.get(Calendar.YEAR));
    ....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.