Reputation: 95
Is there any alternative to TimeZone.getTimeZone()
in Java, since getTimeZone()
is synchronized
, causing my program/application to scale down.
public static synchronized TimeZone getTimeZone(String ID) {
return getTimeZone(ID, true);
}
Upvotes: 2
Views: 1505
Reputation: 86399
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?
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);
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 4
Reputation: 19910
What about TimeZone.getTimeZone(ZoneId)
. Which is not synchronized:
// JDK 8 source
public static TimeZone getTimeZone(ZoneId zoneId) {
String tzid = zoneId.getId(); // throws an NPE if null
char c = tzid.charAt(0);
if (c == '+' || c == '-') {
tzid = "GMT" + tzid;
} else if (c == 'Z' && tzid.length() == 1) {
tzid = "UTC";
}
return getTimeZone(tzid, true);
}
See the following example:
TimeZone timeZone = TimeZone.getTimeZone(ZoneId.of("Europe"));
Upvotes: 0