I should like to contribute the modern answer. The Date
and SimpleDateFormat
classes used in the question are long outdated, and today we have so much better. I recommend the modern Java date and time API known as JSR-310 or java.time
:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss Z");
System.out.println(ZonedDateTime.parse("2015-03-17 06:00:00 +0000", formatter)
.withZoneSameInstant(ZoneId.systemDefault())
.format(formatter));
On my computer in the Europe/Copenhagen time zone this prints
2015-03-17 07:00:00 +0100
Using ZoneId.systemDefault()
is fragile, though, since any program running on the JVM can change its default time zone and thereby alter the behaviour of the above snippet. If you can, it’s better to use a time zone ID in the region/city format, for example ZoneId.of("Asia/Tomsk")
or ZoneId.of("America/Argentina/Rio_Gallegos")
.
Question: Can I use the modern API with my Java version?
If using at least Java 6, you can.
- In Java 8 and later the new API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (that’s ThreeTen for JSR-310, where the modern API was first defined).
- On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP, and I think that there’s a wonderful explanation in this question: How to use ThreeTenABP in Android Project.