SimpleDateFormat format different results

Different value when formatting a date to a string on different machines.

Calendar date = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+03:00"));
sdf.format(date.getTime());

Yyyy-MM-dd'T'HH:mm:ssXXX should return the date as a String, where XXX is +TimeZone, i.e. +03: 00

One machine gets the correct result 2018-06-08T13:47:16+03:00, and the other machine gets the wrong result 2018-06-08T13:47:16Z.

Who can tell you what the reason is?

java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
Author: Senior Pomidor, 2018-06-08

2 answers

A long time ago, I once touched on a similar issue, there was a problem that timezone in Windows was some kind of curve.

It was fixed simply:

TimeZone tz=TimeZone.getTimeZone("GMT+03"); //вместо GMT+03:00

Yes, and check the lists TimeZone.getAvailableIds(3*60*60*1000) on different machines, they will be different (taken from the OS)

 2
Author: Barmaley, 2018-06-09 06:33:15

Since you are using java 8, I would advise you to try using the API that the JDK itself already provides in the java.time package. I think this is a more native approach. Try using this code:

DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
ZonedDateTime.now().format(formatter);

I hope this solves your problem, even if it doesn't answer the question of why your version doesn't work.

 1
Author: Mikita Berazouski, 2018-06-08 17:28:38