Search code examples
javaxmlgregoriancalendar

Java XMLGregorianCalendar is changing the time - Strange behavior


I have a date as input = 2021-03-12T10:42:01.000Z.... and I want to transform into this format:

String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";


public String getDate(XMLGregorianCalendar input) {
    DateFormat f = new SimpleDateFormat(pattern);
    input.toGregorianCalendar().setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
    String output = f.format(input.toGregorianCalendar().getTime());
    System.out.println(output);
}

2021-03-12T12:42:01+0200

Basically, it's adding 2hs more. Maybe it's related with the time zone, I didn't test it in another computer. I have 2 questions:

  • Why this is happening
  • What can I do to avoid it? It's a legacy app so I don't want to do a big change

Thanks


Solution

  • Basically, it's adding 2hs more

    Not really. It's giving you the output for the same instant in time, but in your system local time zone - because you're creating a SimpleDateFormat without specifying a time zone (or a culture):

    DateFormat f = new SimpleDateFormat(pattern);
    

    Personally I'd recommend avoiding using java.text.SimpleDateFormat entirely, preferring the java.time types and formatters. But if you definitely want to use SimpleDateFormat, just make sure you set the time zone to UTC (assuming you always want UTC) and ideally set the culture as well (e.g. to Locale.ROOT).