Formatting XmlGregorianCalendar timezone issue

15,731

It was parsed as midnight on April 15th UTC. It was then formatted as 8pm on April 14th EDT, which is correct as EDT is four hours behind UTC.

Note that Date.toString() always uses the local time zone - a Date object has no concept of which time zone it's in.

Your formatted value is also using the default time zone, as you haven't specified a time zone. The calendar value (gc) is in UTC, but when you format it, it will apply the time zone from the formatter (as you format the Date value, which doesn't have a time zone).

It's not clear what you were trying to achieve, but hopefully that will help. As an aside, I'd strongly recommend that you use Joda Time instead if you possibly can - it makes a lot of this much clearer.

Share:
15,731
ninja
Author by

ninja

Web developer (server-side Java and client-side HTML/CSS/JS)

Updated on June 10, 2022

Comments

  • ninja
    ninja almost 2 years

    I need to format java XmlGregorianCalendar to "yyMMdd" string. My implementation:

    XMLGregorianCalendar date = getDate(); //getting the date
    
    if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
    
            LOG.debug("Parsing date...");
            LOG.debug("XML Date: " + date);
            LOG.debug("XML Date timezone: " + date.getTimezone());
    
            GregorianCalendar gc = date.toGregorianCalendar();
    
            LOG.debug("Gregorian calendar: " + gc.toString());
            LOG.debug("Gregorian calendar timezone id: " + gc.getTimeZone().getID());
    
            Date d = gc.getTime();
    
            LOG.debug("Date: " + d.toString());
    
            String formatted = sdf.format(d);
    
            LOG.debug("Formatted: " + formatted);
    }
    

    What I see in log:

    Parsing date...
    XML Date: 1943-04-15T00:00:00.000Z
    XML Date timezone: 0
    Gregorian calendar: java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+00:00",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=1943,MONTH=3,WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=15,DAY_OF_YEAR=1,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]
    Gregorian calendar timezone id: GMT+00:00
    Date: Wed Apr 14 20:00:00 EDT 1943
    Formatted: 430414
    

    April, 15 was parsed as April, 14. What I'm doing wrong? When I should set timezone?

  • ninja
    ninja about 12 years
    I was trying to parse it with timezone from XmlCalendar. Now I understood that I should set timezone to my formatter. Thanks for explanation.