You don’t want to use TimeZone
in 2018. Modern example:
ZoneId zone = ZoneId.of("America/Dawson_Creek");
The date and time classes from Java 1.0 and 1.1 — Date
, Calendar
, SimpleDateFormat
and also TimeZone
— are long outdated and were never well designed. java.time
, the modern Java date and time API has been included with Java since Java 8 (out four years ago). It replaces them and is much nicer to work with.
If you thought you needed a TimeZone
, for example for setting the time zone of a Calendar
, this class too has been replaced (they all have, as I said). Instead use the modern ZonedDateTime
:
ZonedDateTime dateTime = ZonedDateTime
.parse("2018-06-22T01:23:31.615464+11:00[Pacific/Guadalcanal]");
ZonedDateTime converted = dateTime.withZoneSameInstant(zone);
System.out.println("2018-06-22T01:23:31.615464 in Guadalcanal = " + converted);
Output:
2018-06-22T01:23:31.615464 in Guadalcanal =
2018-06-21T07:23:31.615464-07:00[America/Dawson_Creek]
It may of course occur that you need an old-fashioned TimeZone
object for a legacy API that you either cannot change or don’t want to change just now. In that case use the conversion that Lino pointed out in another answer:
TimeZone oldfashionedTimeZone = TimeZone.getTimeZone(zone);
System.out.println(oldfashionedTimeZone);
sun.util.calendar.ZoneInfo[id="America/Dawson_Creek",offset=-25200000,dstSavings=0,useDaylight=false,transitions=58,lastRule=null]
If your problem is that the synchronization of TimeZone.getTimeZone(String)
is slowing your program down, I am wondering how many TimeZone
objects you are creating? With just 600 available time zone IDs (in my Java 10), I don’t think you need that many. I still clearly recommend ZoneId
over TimeZone
, but if the creation takes too long, caching them might be a better option?
Question: But what if I am using Java 6 or 7?
No big problem. java.time
works nicely on Java 6 and 7 too. Only the conversions to the outdated classes are different, for example:
TimeZone oldfashionedTimeZone = DateTimeUtils.toTimeZone(zone);
- In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links