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
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
SimpleDateFormatwithout specifying a time zone (or a culture):Personally I'd recommend avoiding using
java.text.SimpleDateFormatentirely, preferring thejava.timetypes and formatters. But if you definitely want to useSimpleDateFormat, just make sure you set the time zone to UTC (assuming you always want UTC) and ideally set the culture as well (e.g. toLocale.ROOT).