2 * @(#)TimeZone.java 1.51 00/01/19
4 * Copyright (C) 1996-2013, International Business Machines
5 * Corporation and others. All Rights Reserved.
8 package com.ibm.icu.util;
10 import java.io.Serializable;
11 import java.util.Date;
12 import java.util.Locale;
13 import java.util.MissingResourceException;
15 import java.util.logging.Logger;
17 import com.ibm.icu.impl.Grego;
18 import com.ibm.icu.impl.ICUConfig;
19 import com.ibm.icu.impl.ICUResourceBundle;
20 import com.ibm.icu.impl.JavaTimeZone;
21 import com.ibm.icu.impl.TimeZoneAdapter;
22 import com.ibm.icu.impl.ZoneMeta;
23 import com.ibm.icu.text.TimeZoneFormat;
24 import com.ibm.icu.text.TimeZoneFormat.Style;
25 import com.ibm.icu.text.TimeZoneFormat.TimeType;
26 import com.ibm.icu.text.TimeZoneNames;
27 import com.ibm.icu.text.TimeZoneNames.NameType;
28 import com.ibm.icu.util.ULocale.Category;
31 * {@icuenhanced java.util.TimeZone}.{@icu _usage_}
33 * <p><code>TimeZone</code> represents a time zone offset, and also computes daylight
36 * <p>Typically, you get a <code>TimeZone</code> using {@link #getDefault()}
37 * which creates a <code>TimeZone</code> based on the time zone where the program
38 * is running. For example, for a program running in Japan, <code>getDefault</code>
39 * creates a <code>TimeZone</code> object based on Japanese Standard Time.
41 * <p>You can also get a <code>TimeZone</code> using {@link #getTimeZone(String)}
42 * along with a time zone ID. For instance, the time zone ID for the
43 * U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a
44 * U.S. Pacific Time <code>TimeZone</code> object with:
48 * TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
51 * You can use the {@link #getAvailableIDs()} method to iterate through
52 * all the supported time zone IDs, or getCanonicalID method to check
53 * if a time zone ID is supported or not. You can then choose a
54 * supported ID to get a <code>TimeZone</code>.
55 * If the time zone you want is not represented by one of the
56 * supported IDs, then you can create a custom time zone ID with
57 * the following syntax:
65 * For example, you might specify GMT+14:00 as a custom
66 * time zone ID. The <code>TimeZone</code> that is returned
67 * when you specify a custom time zone ID uses the specified
68 * offset from GMT(=UTC) and does not observe daylight saving
69 * time. For example, you might specify GMT+14:00 as a custom
70 * time zone ID to create a TimeZone representing 14 hours ahead
71 * of GMT (with no daylight saving time). In addition,
72 * <code>getCanonicalID</code> can also be used to
73 * normalize a custom time zone ID.
75 * <p>For compatibility with JDK 1.1.x, some other three-letter time zone IDs
76 * (such as "PST", "CTT", "AST") are also supported. However, <strong>their
77 * use is deprecated</strong> because the same abbreviation is often used
78 * for multiple time zones (for example, "CST" could be U.S. "Central Standard
79 * Time" and "China Standard Time"), and the Java platform can then only
80 * recognize one of them.
82 * <p><strong>Note:</strong> Starting from ICU4J 4.0, you can optionally choose
83 * JDK <code>TimeZone</code> as the time zone implementation. The TimeZone factory
84 * method <code>getTimeZone</code> creates an instance of ICU's own <code>TimeZone</code>
85 * subclass by default. If you want to use the JDK implementation always, you can
86 * set the default time zone implementation type by the new method
87 * <code>setDefaultTimeZoneType</code>. Alternatively, you can change the initial
88 * default implementation type by setting a property below.
93 * # The default TimeZone implementation type used by the ICU TimeZone
94 * # factory method. [ ICU | JDK ]
96 * com.ibm.icu.util.TimeZone.DefaultTimeZoneType = ICU
100 * <p>This property is included in ICUConfig.properties in com.ibm.icu package. When the
101 * <code>TimeZone</code> class is loaded, the initialization code checks if the property
102 * <code>com.ibm.icu.util.TimeZone.DefaultTimeZoneType=xxx</code> is defined by the system
103 * properties. If not available, then it loads ICUConfig.properties to get the default
104 * time zone implementation type. The property setting is only used for the initial
105 * default value and you can change the default type by calling
106 * <code>setDefaultTimeZoneType</code> at runtime.
109 * @see GregorianCalendar
110 * @see SimpleTimeZone
111 * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
114 abstract public class TimeZone implements Serializable, Cloneable, Freezable<TimeZone> {
116 * Logger instance for this class
118 private static final Logger LOGGER = Logger.getLogger("com.ibm.icu.util.TimeZone");
120 // using serialver from jdk1.4.2_05
121 private static final long serialVersionUID = -744942128318337471L;
124 * Default constructor. (For invocation by subclass constructors,
125 * typically implicit.)
132 * Constructing a TimeZone with the given time zone ID.
133 * @param ID the time zone ID.
135 * @deprecated This API is ICU internal only.
137 protected TimeZone(String ID) {
139 throw new NullPointerException();
145 * {@icu} A time zone implementation type indicating ICU's own TimeZone used by
146 * <code>getTimeZone</code>, <code>setDefaultTimeZoneType</code>
147 * and <code>getDefaultTimeZoneType</code>.
150 public static final int TIMEZONE_ICU = 0;
152 * {@icu} A time zone implementation type indicating JDK TimeZone used by
153 * <code>getTimeZone</code>, <code>setDefaultTimeZoneType</code>
154 * and <code>getDefaultTimeZoneType</code>.
157 public static final int TIMEZONE_JDK = 1;
160 * A style specifier for <code>getDisplayName()</code> indicating
161 * a short name, such as "PST."
165 public static final int SHORT = 0;
168 * A style specifier for <code>getDisplayName()</code> indicating
169 * a long name, such as "Pacific Standard Time."
173 public static final int LONG = 1;
176 * {@icu} A style specifier for <code>getDisplayName()</code> indicating
177 * a short generic name, such as "PT."
181 public static final int SHORT_GENERIC = 2;
184 * {@icu} A style specifier for <code>getDisplayName()</code> indicating
185 * a long generic name, such as "Pacific Time."
186 * @see #SHORT_GENERIC
189 public static final int LONG_GENERIC = 3;
192 * {@icu} A style specifier for <code>getDisplayName()</code> indicating
193 * a short name derived from the timezone's offset, such as "-0800."
197 public static final int SHORT_GMT = 4;
200 * {@icu} A style specifier for <code>getDisplayName()</code> indicating
201 * a long name derived from the timezone's offset, such as "GMT-08:00."
205 public static final int LONG_GMT = 5;
208 * {@icu} A style specifier for <code>getDisplayName()</code> indicating
209 * a short name derived from the timezone's short standard or daylight
210 * timezone name ignoring commonlyUsed, such as "PDT."
214 public static final int SHORT_COMMONLY_USED = 6;
217 * {@icu} A style specifier for <code>getDisplayName()</code> indicating
218 * a long name derived from the timezone's fallback name, such as
219 * "United States (Los Angeles)."
222 public static final int GENERIC_LOCATION = 7;
225 * {@icu} The time zone ID reserved for unknown time zone.
226 * @see #getTimeZone(String)
230 public static final String UNKNOWN_ZONE_ID = "Etc/Unknown";
233 * The canonical ID for GMT(UTC) time zone.
235 static final String GMT_ZONE_ID = "Etc/GMT";
238 * {@icu} The immutable (frozen) "unknown" time zone.
239 * It behaves like the GMT/UTC time zone but has the UNKNOWN_ZONE_ID = "Etc/Unknown".
240 * {@link TimeZone#getTimeZone(String)} returns a mutable clone of this
241 * time zone if the input ID is not recognized.
243 * @see #UNKNOWN_ZONE_ID
244 * @see #getTimeZone(String)
248 public static final TimeZone UNKNOWN_ZONE = new SimpleTimeZone(0, UNKNOWN_ZONE_ID).freeze();
251 * {@icu} The immutable GMT (=UTC) time zone. Its ID is "Etc/GMT".
255 public static final TimeZone GMT_ZONE = new SimpleTimeZone(0, GMT_ZONE_ID).freeze();
258 * {@icu} System time zone type constants used by filtering zones in
259 * {@link TimeZone#getAvailableIDs(SystemTimeZoneType, String, Integer)}
263 public enum SystemTimeZoneType {
267 * @provisional This API might change or be removed in a future release.
272 * Canonical system zones.
274 * @provisional This API might change or be removed in a future release.
279 * Canonical system zones associated with actual locations.
281 * @provisional This API might change or be removed in a future release.
287 * Gets the time zone offset, for current date, modified in case of
288 * daylight savings. This is the offset to add *to* UTC to get local time.
289 * @param era the era of the given date.
290 * @param year the year in the given date.
291 * @param month the month in the given date.
292 * Month is 0-based. e.g., 0 for January.
293 * @param day the day-in-month of the given date.
294 * @param dayOfWeek the day-of-week of the given date.
295 * @param milliseconds the millis in day in <em>standard</em> local time.
296 * @return the offset to add *to* GMT to get local time.
299 abstract public int getOffset(int era, int year, int month, int day,
300 int dayOfWeek, int milliseconds);
304 * Returns the offset of this time zone from UTC at the specified
305 * date. If Daylight Saving Time is in effect at the specified
306 * date, the offset value is adjusted with the amount of daylight
309 * @param date the date represented in milliseconds since January 1, 1970 00:00:00 GMT
310 * @return the amount of time in milliseconds to add to UTC to get local time.
312 * @see Calendar#ZONE_OFFSET
313 * @see Calendar#DST_OFFSET
314 * @see #getOffset(long, boolean, int[])
317 public int getOffset(long date) {
318 int[] result = new int[2];
319 getOffset(date, false, result);
320 return result[0]+result[1];
324 * Returns the time zone raw and GMT offset for the given moment
325 * in time. Upon return, local-millis = GMT-millis + rawOffset +
326 * dstOffset. All computations are performed in the proleptic
327 * Gregorian calendar. The default implementation in the TimeZone
328 * class delegates to the 8-argument getOffset().
330 * @param date moment in time for which to return offsets, in
331 * units of milliseconds from January 1, 1970 0:00 GMT, either GMT
332 * time or local wall time, depending on `local'.
333 * @param local if true, `date' is local wall time; otherwise it
335 * @param offsets output parameter to receive the raw offset, that
336 * is, the offset not including DST adjustments, in offsets[0],
337 * and the DST offset, that is, the offset to be added to
338 * `rawOffset' to obtain the total offset between local and GMT
339 * time, in offsets[1]. If DST is not in effect, the DST offset is
340 * zero; otherwise it is a positive value, typically one hour.
344 public void getOffset(long date, boolean local, int[] offsets) {
345 offsets[0] = getRawOffset();
347 date += offsets[0]; // now in local standard millis
350 // When local == true, date might not be in local standard
351 // millis. getOffset taking 6 parameters used here assume
352 // the given time in day is local standard time.
353 // At STD->DST transition, there is a range of time which
354 // does not exist. When 'date' is in this time range
355 // (and local == true), this method interprets the specified
356 // local time as DST. At DST->STD transition, there is a
357 // range of time which occurs twice. In this case, this
358 // method interprets the specified local time as STD.
359 // To support the behavior above, we need to call getOffset
360 // (with 6 args) twice when local == true and DST is
361 // detected in the initial call.
362 int fields[] = new int[6];
363 for (int pass = 0; ; pass++) {
364 Grego.timeToFields(date, fields);
365 offsets[1] = getOffset(GregorianCalendar.AD,
366 fields[0], fields[1], fields[2],
367 fields[3], fields[5]) - offsets[0];
369 if (pass != 0 || !local || offsets[1] == 0) {
372 // adjust to local standard millis
378 * Sets the base time zone offset to GMT.
379 * This is the offset to add *to* UTC to get local time.
380 * @param offsetMillis the given base time zone offset to GMT.
383 abstract public void setRawOffset(int offsetMillis);
386 * Gets unmodified offset, NOT modified in case of daylight savings.
387 * This is the offset to add *to* UTC to get local time.
388 * @return the unmodified offset to add *to* UTC to get local time.
391 abstract public int getRawOffset();
394 * Gets the ID of this time zone.
395 * @return the ID of this time zone.
398 public String getID() {
403 * Sets the time zone ID. This does not change any other data in
404 * the time zone object.
405 * @param ID the new time zone ID.
408 public void setID(String ID) {
410 throw new NullPointerException();
413 throw new UnsupportedOperationException("Attempt to modify a frozen TimeZone instance.");
419 * Returns a name of this time zone suitable for presentation to the user
420 * in the default <code>DISPLAY</code> locale.
421 * This method returns the long generic name.
422 * If the display name is not available for the locale,
423 * a fallback based on the country, city, or time zone id will be used.
424 * @return the human-readable name of this time zone in the default locale.
425 * @see Category#DISPLAY
428 public final String getDisplayName() {
429 return _getDisplayName(LONG_GENERIC, false, ULocale.getDefault(Category.DISPLAY));
433 * Returns a name of this time zone suitable for presentation to the user
434 * in the specified locale.
435 * This method returns the long generic name.
436 * If the display name is not available for the locale,
437 * a fallback based on the country, city, or time zone id will be used.
438 * @param locale the locale in which to supply the display name.
439 * @return the human-readable name of this time zone in the given locale
440 * or in the default locale if the given locale is not recognized.
443 public final String getDisplayName(Locale locale) {
444 return _getDisplayName(LONG_GENERIC, false, ULocale.forLocale(locale));
448 * Returns a name of this time zone suitable for presentation to the user
449 * in the specified locale.
450 * This method returns the long name, not including daylight savings.
451 * If the display name is not available for the locale,
452 * a fallback based on the country, city, or time zone id will be used.
453 * @param locale the ulocale in which to supply the display name.
454 * @return the human-readable name of this time zone in the given locale
455 * or in the default ulocale if the given ulocale is not recognized.
458 public final String getDisplayName(ULocale locale) {
459 return _getDisplayName(LONG_GENERIC, false, locale);
463 * Returns a name of this time zone suitable for presentation to the user
464 * in the default <code>DISPLAY</code> locale.
465 * If the display name is not available for the locale,
466 * then this method returns a string in the localized GMT offset format
467 * such as <code>GMT[+-]HH:mm</code>.
468 * @param daylight if true, return the daylight savings name.
469 * @param style the output style of the display name. Valid styles are
470 * <code>SHORT</code>, <code>LONG</code>, <code>SHORT_GENERIC</code>,
471 * <code>LONG_GENERIC</code>, <code>SHORT_GMT</code>, <code>LONG_GMT</code>,
472 * <code>SHORT_COMMONLY_USED</code> or <code>GENERIC_LOCATION</code>.
473 * @return the human-readable name of this time zone in the default locale.
474 * @see Category#DISPLAY
477 public final String getDisplayName(boolean daylight, int style) {
478 return getDisplayName(daylight, style, ULocale.getDefault(Category.DISPLAY));
482 * Returns a name of this time zone suitable for presentation to the user
483 * in the specified locale.
484 * If the display name is not available for the locale,
485 * then this method returns a string in the localized GMT offset format
486 * such as <code>GMT[+-]HH:mm</code>.
487 * @param daylight if true, return the daylight savings name.
488 * @param style the output style of the display name. Valid styles are
489 * <code>SHORT</code>, <code>LONG</code>, <code>SHORT_GENERIC</code>,
490 * <code>LONG_GENERIC</code>, <code>SHORT_GMT</code>, <code>LONG_GMT</code>,
491 * <code>SHORT_COMMONLY_USED</code> or <code>GENERIC_LOCATION</code>.
492 * @param locale the locale in which to supply the display name.
493 * @return the human-readable name of this time zone in the given locale
494 * or in the default locale if the given locale is not recognized.
495 * @exception IllegalArgumentException style is invalid.
498 public String getDisplayName(boolean daylight, int style, Locale locale) {
499 return getDisplayName(daylight, style, ULocale.forLocale(locale));
503 * Returns a name of this time zone suitable for presentation to the user
504 * in the specified locale.
505 * If the display name is not available for the locale,
506 * then this method returns a string in the localized GMT offset format
507 * such as <code>GMT[+-]HH:mm</code>.
508 * @param daylight if true, return the daylight savings name.
509 * @param style the output style of the display name. Valid styles are
510 * <code>SHORT</code>, <code>LONG</code>, <code>SHORT_GENERIC</code>,
511 * <code>LONG_GENERIC</code>, <code>SHORT_GMT</code>, <code>LONG_GMT</code>,
512 * <code>SHORT_COMMONLY_USED</code> or <code>GENERIC_LOCATION</code>.
513 * @param locale the locale in which to supply the display name.
514 * @return the human-readable name of this time zone in the given locale
515 * or in the default locale if the given locale is not recognized.
516 * @exception IllegalArgumentException style is invalid.
519 public String getDisplayName(boolean daylight, int style, ULocale locale) {
520 if (style < SHORT || style > GENERIC_LOCATION) {
521 throw new IllegalArgumentException("Illegal style: " + style);
524 return _getDisplayName(style, daylight, locale);
528 * internal version (which is called by public APIs) accepts
529 * SHORT, LONG, SHORT_GENERIC, LONG_GENERIC, SHORT_GMT, LONG_GMT,
530 * SHORT_COMMONLY_USED and GENERIC_LOCATION.
532 private String _getDisplayName(int style, boolean daylight, ULocale locale) {
533 if (locale == null) {
534 throw new NullPointerException("locale is null");
537 String result = null;
539 if (style == GENERIC_LOCATION || style == LONG_GENERIC || style == SHORT_GENERIC) {
541 TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(locale);
542 long date = System.currentTimeMillis();
543 Output<TimeType> timeType = new Output<TimeType>(TimeType.UNKNOWN);
546 case GENERIC_LOCATION:
547 result = tzfmt.format(Style.GENERIC_LOCATION, this, date, timeType);
550 result = tzfmt.format(Style.GENERIC_LONG, this, date, timeType);
553 result = tzfmt.format(Style.GENERIC_SHORT, this, date, timeType);
557 // Generic format many use Localized GMT as the final fallback.
558 // When Localized GMT format is used, the result might not be
559 // appropriate for the requested daylight value.
560 if (daylight && timeType.value == TimeType.STANDARD ||
561 !daylight && timeType.value == TimeType.DAYLIGHT) {
562 int offset = daylight ? getRawOffset() + getDSTSavings() : getRawOffset();
563 result = (style == SHORT_GENERIC) ?
564 tzfmt.formatOffsetShortLocalizedGMT(offset) : tzfmt.formatOffsetLocalizedGMT(offset);
567 } else if (style == LONG_GMT || style == SHORT_GMT) {
569 TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(locale);
570 int offset = daylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
573 result = tzfmt.formatOffsetLocalizedGMT(offset);
576 result = tzfmt.formatOffsetISO8601Basic(offset, false, false, false);
581 assert(style == LONG || style == SHORT || style == SHORT_COMMONLY_USED);
583 // Gets the name directly from TimeZoneNames
584 long date = System.currentTimeMillis();
585 TimeZoneNames tznames = TimeZoneNames.getInstance(locale);
586 NameType nameType = null;
589 nameType = daylight ? NameType.LONG_DAYLIGHT : NameType.LONG_STANDARD;
592 case SHORT_COMMONLY_USED:
593 nameType = daylight ? NameType.SHORT_DAYLIGHT : NameType.SHORT_STANDARD;
596 result = tznames.getDisplayName(ZoneMeta.getCanonicalCLDRID(this), nameType, date);
597 if (result == null) {
598 // Fallback to localized GMT
599 TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(locale);
600 int offset = daylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
601 result = (style == LONG) ?
602 tzfmt.formatOffsetLocalizedGMT(offset) : tzfmt.formatOffsetShortLocalizedGMT(offset);
605 assert(result != null);
611 * Returns the amount of time to be added to local standard time
612 * to get local wall clock time.
614 * The default implementation always returns 3600000 milliseconds
615 * (i.e., one hour) if this time zone observes Daylight Saving
616 * Time. Otherwise, 0 (zero) is returned.
618 * If an underlying TimeZone implementation subclass supports
619 * historical Daylight Saving Time changes, this method returns
620 * the known latest daylight saving value.
622 * @return the amount of saving time in milliseconds
625 public int getDSTSavings() {
626 if (useDaylightTime()) {
633 * Queries if this time zone uses daylight savings time.
634 * @return true if this time zone uses daylight savings time,
636 * <p><strong>Note:</strong>The default implementation of
637 * ICU TimeZone uses the tz database, which supports historic
638 * rule changes, for system time zones. With the implementation,
639 * there are time zones that used daylight savings time in the
640 * past, but no longer used currently. For example, Asia/Tokyo has
641 * never used daylight savings time since 1951. Most clients would
642 * expect that this method to return <code>false</code> for such case.
643 * The default implementation of this method returns <code>true</code>
644 * when the time zone uses daylight savings time in the current
645 * (Gregorian) calendar year.
648 abstract public boolean useDaylightTime();
651 * Queries if this time zone is in daylight saving time or will observe
652 * daylight saving time at any future time.
653 * <p>The default implementation in this class returns <code>true</code> if {@link #useDaylightTime()}
654 * or {@link #inDaylightTime(Date) inDaylightTime(new Date())} returns <code>true</code>.
656 * <strong>Note:</strong> This method was added for JDK compatibility support.
657 * The JDK's <code>useDaylightTime()</code> only checks the last known rule(s), therefore
658 * it may return false even the zone observes daylight saving time currently. JDK added
659 * <code>observesDaylightTime()</code> to resolve the issue. In ICU, {@link #useDaylightTime()}
660 * works differently. The ICU implementation checks if the zone uses daylight saving time
661 * in the current calendar year. Therefore, it will never return <code>false</code> if
662 * daylight saving time is currently used.
664 * ICU's TimeZone subclass implementations override this method to support the same behavior
665 * with JDK's <code>observesDaylightSavingTime()</code>. Unlike {@link #useDaylightTime()},
666 * the implementation does not take past daylight saving time into account, so
667 * that this method may return <code>false</code> even when {@link #useDaylightTime()} returns
670 * @return <code>true</code> if this time zone is in daylight saving time or will observe
671 * daylight saving time at any future time.
672 * @see #useDaylightTime
675 public boolean observesDaylightTime() {
676 return useDaylightTime() || inDaylightTime(new Date());
680 * Queries if the given date is in daylight savings time in
682 * @param date the given Date.
683 * @return true if the given date is in daylight savings time,
687 abstract public boolean inDaylightTime(Date date);
690 * Gets the <code>TimeZone</code> for the given ID.
692 * @param ID the ID for a <code>TimeZone</code>, such as "America/Los_Angeles",
693 * or a custom ID such as "GMT-8:00". Note that the support of abbreviations,
694 * such as "PST", is for JDK 1.1.x compatibility only and full names should be used.
696 * @return the specified <code>TimeZone</code>, or a mutable clone of the UNKNOWN_ZONE
697 * if the given ID cannot be understood or if the given ID is "Etc/Unknown".
701 public static TimeZone getTimeZone(String ID) {
702 return getTimeZone(ID, TZ_IMPL, false);
706 * Gets the <code>TimeZone</code> for the given ID. The instance of <code>TimeZone</code>
707 * returned by this method is immutable. Any methods mutate the instance({@link #setID(String)},
708 * {@link #setRawOffset(int)}) will throw <code>UnsupportedOperationException</code> upon its
711 * @param ID the ID for a <code>TimeZone</code>, such as "America/Los_Angeles",
712 * or a custom ID such as "GMT-8:00". Note that the support of abbreviations,
713 * such as "PST", is for JDK 1.1.x compatibility only and full names should be used.
715 * @return the specified <code>TimeZone</code>, or the UNKNOWN_ZONE
716 * if the given ID cannot be understood.
720 public static TimeZone getFrozenTimeZone(String ID) {
721 return getTimeZone(ID, TZ_IMPL, true);
725 * Gets the <code>TimeZone</code> for the given ID and the timezone type.
726 * @param ID the ID for a <code>TimeZone</code>, such as "America/Los_Angeles", or a
727 * custom ID such as "GMT-8:00". Note that the support of abbreviations, such as
728 * "PST", is for JDK 1.1.x compatibility only and full names should be used.
729 * @param type Time zone type, either <code>TIMEZONE_ICU</code> or
730 * <code>TIMEZONE_JDK</code>.
731 * @return the specified <code>TimeZone</code>, or a mutable clone of the UNKNOWN_ZONE if the given ID
732 * cannot be understood or if the given ID is "Etc/Unknown".
736 public static TimeZone getTimeZone(String ID, int type) {
737 return getTimeZone(ID, type, false);
741 * Gets the <code>TimeZone</code> for the given ID and the timezone type.
742 * @param ID time zone ID
743 * @param type time zone implementation type, TIMEZONE_JDK or TIMEZONE_ICU
744 * @param frozen specify if the returned object can be frozen
745 * @return the specified <code>TimeZone</code> or UNKNOWN_ZONE if the given ID
746 * cannot be understood.
748 private static synchronized TimeZone getTimeZone(String ID, int type, boolean frozen) {
750 if (type == TIMEZONE_JDK) {
751 result = JavaTimeZone.createTimeZone(ID);
752 if (result != null) {
753 return frozen ? result.freeze() : result;
756 /* We first try to lookup the zone ID in our system list. If this
757 * fails, we try to parse it as a custom string GMT[+-]HH:mm. If
758 * all else fails, we return GMT, which is probably not what the
759 * user wants, but at least is a functioning TimeZone object.
761 * We cannot return NULL, because that would break compatibility
765 throw new NullPointerException();
767 result = ZoneMeta.getSystemTimeZone(ID);
770 if (result == null) {
771 result = ZoneMeta.getCustomTimeZone(ID);
774 if (result == null) {
775 LOGGER.fine("\"" +ID + "\" is a bogus id so timezone is falling back to Etc/Unknown(GMT).");
776 result = UNKNOWN_ZONE;
779 return frozen ? result : result.cloneAsThawed();
783 * Sets the default time zone type used by <code>getTimeZone</code>.
784 * @param type time zone type, either <code>TIMEZONE_ICU</code> or
785 * <code>TIMEZONE_JDK</code>.
788 public static synchronized void setDefaultTimeZoneType(int type) {
789 if (type != TIMEZONE_ICU && type != TIMEZONE_JDK) {
790 throw new IllegalArgumentException("Invalid timezone type");
796 * {@icu} Returns the default time zone type currently used.
797 * @return The default time zone type, either <code>TIMEZONE_ICU</code> or
798 * <code>TIMEZONE_JDK</code>.
801 public static int getDefaultTimeZoneType() {
806 * {@icu} Returns a set of time zone ID strings with the given filter conditions.
807 * <p><b>Note:</b>A <code>Set</code> returned by this method is
809 * @param zoneType The system time zone type.
810 * @param region The ISO 3166 two-letter country code or UN M.49 three-digit area code.
811 * When null, no filtering done by region.
812 * @param rawOffset An offset from GMT in milliseconds, ignoring the effect of daylight savings
813 * time, if any. When null, no filtering done by zone offset.
814 * @return an immutable set of system time zone IDs.
815 * @see SystemTimeZoneType
819 public static Set<String> getAvailableIDs(SystemTimeZoneType zoneType,
820 String region, Integer rawOffset) {
821 return ZoneMeta.getAvailableIDs(zoneType, region, rawOffset);
825 * Return a new String array containing all system TimeZone IDs
826 * with the given raw offset from GMT. These IDs may be passed to
827 * <code>get()</code> to construct the corresponding TimeZone
829 * @param rawOffset the offset in milliseconds from GMT
830 * @return an array of IDs for system TimeZones with the given
831 * raw offset. If there are none, return a zero-length array.
832 * @see #getAvailableIDs(SystemTimeZoneType, String, Integer)
836 public static String[] getAvailableIDs(int rawOffset) {
837 Set<String> ids = getAvailableIDs(SystemTimeZoneType.ANY, null, Integer.valueOf(rawOffset));
838 return ids.toArray(new String[0]);
842 * Return a new String array containing all system TimeZone IDs
843 * associated with the given country. These IDs may be passed to
844 * <code>get()</code> to construct the corresponding TimeZone
846 * @param country a two-letter ISO 3166 country code, or <code>null</code>
847 * to return zones not associated with any country
848 * @return an array of IDs for system TimeZones in the given
849 * country. If there are none, return a zero-length array.
850 * @see #getAvailableIDs(SystemTimeZoneType, String, Integer)
854 public static String[] getAvailableIDs(String country) {
855 Set<String> ids = getAvailableIDs(SystemTimeZoneType.ANY, country, null);
856 return ids.toArray(new String[0]);
860 * Return a new String array containing all system TimeZone IDs.
861 * These IDs (and only these IDs) may be passed to
862 * <code>get()</code> to construct the corresponding TimeZone
864 * @return an array of all system TimeZone IDs
865 * @see #getAvailableIDs(SystemTimeZoneType, String, Integer)
869 public static String[] getAvailableIDs() {
870 Set<String> ids = getAvailableIDs(SystemTimeZoneType.ANY, null, null);
871 return ids.toArray(new String[0]);
875 * {@icu} Returns the number of IDs in the equivalency group that
876 * includes the given ID. An equivalency group contains zones
877 * that have the same GMT offset and rules.
879 * <p>The returned count includes the given ID; it is always >= 1
880 * for valid IDs. The given ID must be a system time zone. If it
881 * is not, returns zero.
882 * @param id a system time zone ID
883 * @return the number of zones in the equivalency group containing
884 * 'id', or zero if 'id' is not a valid system ID
885 * @see #getEquivalentID
888 public static int countEquivalentIDs(String id) {
889 return ZoneMeta.countEquivalentIDs(id);
893 * Returns an ID in the equivalency group that
894 * includes the given ID. An equivalency group contains zones
895 * that have the same GMT offset and rules.
897 * <p>The given index must be in the range 0..n-1, where n is the
898 * value returned by <code>countEquivalentIDs(id)</code>. For
899 * some value of 'index', the returned value will be equal to the
900 * given id. If the given id is not a valid system time zone, or
901 * if 'index' is out of range, then returns an empty string.
902 * @param id a system time zone ID
903 * @param index a value from 0 to n-1, where n is the value
904 * returned by <code>countEquivalentIDs(id)</code>
905 * @return the ID of the index-th zone in the equivalency group
906 * containing 'id', or an empty string if 'id' is not a valid
907 * system ID or 'index' is out of range
908 * @see #countEquivalentIDs
911 public static String getEquivalentID(String id, int index) {
912 return ZoneMeta.getEquivalentID(id, index);
916 * Gets the default <code>TimeZone</code> for this host.
917 * The source of the default <code>TimeZone</code>
918 * may vary with implementation.
919 * @return a default <code>TimeZone</code>.
922 public static synchronized TimeZone getDefault() {
923 if (defaultZone == null) {
924 if (TZ_IMPL == TIMEZONE_JDK) {
925 defaultZone = new JavaTimeZone();
927 java.util.TimeZone temp = java.util.TimeZone.getDefault();
928 defaultZone = getFrozenTimeZone(temp.getID());
931 return defaultZone.cloneAsThawed();
935 * Sets the <code>TimeZone</code> that is
936 * returned by the <code>getDefault</code> method. If <code>zone</code>
937 * is null, reset the default to the value it had originally when the
939 * @param tz the new default time zone
942 public static synchronized void setDefault(TimeZone tz) {
944 java.util.TimeZone jdkZone = null;
945 if (defaultZone instanceof JavaTimeZone) {
946 jdkZone = ((JavaTimeZone)defaultZone).unwrap();
948 // Keep java.util.TimeZone default in sync so java.util.Date
949 // can interoperate with com.ibm.icu.util classes.
952 if (tz instanceof com.ibm.icu.impl.OlsonTimeZone) {
953 // Because of the lack of APIs supporting historic
954 // zone offset/dst saving in JDK TimeZone,
955 // wrapping ICU TimeZone with JDK TimeZone will
956 // cause historic offset calculation in Calendar/Date.
957 // JDK calendar implementation calls getRawOffset() and
958 // getDSTSavings() when the instance of JDK TimeZone
959 // is not an instance of JDK internal TimeZone subclass
960 // (sun.util.calendar.ZoneInfo). Ticket#6459
961 String icuID = tz.getID();
962 jdkZone = java.util.TimeZone.getTimeZone(icuID);
963 if (!icuID.equals(jdkZone.getID())) {
964 // JDK does not know the ID..
968 if (jdkZone == null) {
969 jdkZone = TimeZoneAdapter.wrap(tz);
973 java.util.TimeZone.setDefault(jdkZone);
977 * Returns true if this zone has the same rule and offset as another zone.
978 * That is, if this zone differs only in ID, if at all. Returns false
979 * if the other zone is null.
980 * @param other the <code>TimeZone</code> object to be compared with
981 * @return true if the other zone is not null and is the same as this one,
982 * with the possible exception of the ID
985 public boolean hasSameRules(TimeZone other) {
986 return other != null &&
987 getRawOffset() == other.getRawOffset() &&
988 useDaylightTime() == other.useDaylightTime();
995 public Object clone() {
999 return cloneAsThawed();
1006 public boolean equals(Object obj){
1007 if (this == obj) return true;
1008 if (obj == null || getClass() != obj.getClass()) return false;
1009 return (ID.equals(((TimeZone)obj).ID));
1013 * Overrides hashCode.
1016 public int hashCode(){
1017 return ID.hashCode();
1021 * {@icu} Returns the time zone data version currently used by ICU.
1023 * @return the version string, such as "2007f"
1024 * @throws MissingResourceException if ICU time zone resource bundle
1025 * is missing or the version information is not available.
1029 public static synchronized String getTZDataVersion() {
1030 if (TZDATA_VERSION == null) {
1031 UResourceBundle tzbundle = UResourceBundle.getBundleInstance(
1032 "com/ibm/icu/impl/data/icudt" + VersionInfo.ICU_DATA_VERSION_PATH, "zoneinfo64");
1033 TZDATA_VERSION = tzbundle.getString("TZVersion");
1035 return TZDATA_VERSION;
1039 * {@icu} Returns the canonical system time zone ID or the normalized
1040 * custom time zone ID for the given time zone ID.
1041 * @param id The input time zone ID to be canonicalized.
1042 * @return The canonical system time zone ID or the custom time zone ID
1043 * in normalized format for the given time zone ID. When the given time zone ID
1044 * is neither a known system time zone ID nor a valid custom time zone ID,
1048 public static String getCanonicalID(String id) {
1049 return getCanonicalID(id, null);
1053 * {@icu} Returns the canonical system time zone ID or the normalized
1054 * custom time zone ID for the given time zone ID.
1055 * @param id The input time zone ID to be canonicalized.
1056 * @param isSystemID When non-null boolean array is specified and
1057 * the given ID is a known system time zone ID, true is set to <code>isSystemID[0]</code>
1058 * @return The canonical system time zone ID or the custom time zone ID
1059 * in normalized format for the given time zone ID. When the given time zone ID
1060 * is neither a known system time zone ID nor a valid custom time zone ID,
1064 public static String getCanonicalID(String id, boolean[] isSystemID) {
1065 String canonicalID = null;
1066 boolean systemTzid = false;
1067 if (id != null && id.length() != 0) {
1068 if (id.equals(TimeZone.UNKNOWN_ZONE_ID)) {
1069 // special case - Etc/Unknown is a canonical ID, but not system ID
1070 canonicalID = TimeZone.UNKNOWN_ZONE_ID;
1073 canonicalID = ZoneMeta.getCanonicalCLDRID(id);
1074 if (canonicalID != null) {
1077 canonicalID = ZoneMeta.getCustomID(id);
1081 if (isSystemID != null) {
1082 isSystemID[0] = systemTzid;
1088 * {@icu} Returns the region code associated with the given
1089 * system time zone ID. The region code is either ISO 3166
1090 * 2-letter country code or UN M.49 3-digit area code.
1091 * When the time zone is not associated with a specific location,
1092 * for example - "Etc/UTC", "EST5EDT", then this method returns
1093 * "001" (UN M.49 area code for World).
1094 * @param id the system time zone ID.
1095 * @return the region code associated with the given
1096 * system time zone ID.
1097 * @throws IllegalArgumentException if <code>id</code> is not a known system ID.
1098 * @see #getAvailableIDs(String)
1102 public static String getRegion(String id) {
1103 String region = null;
1104 // "Etc/Unknown" is not a system time zone ID,
1105 // but in the zone data.
1106 if (!id.equals(UNKNOWN_ZONE_ID)) {
1107 region = ZoneMeta.getRegion(id);
1109 if (region == null) {
1111 throw new IllegalArgumentException("Unknown system zone id: " + id);
1117 * {@icu} Converts a system time zone ID to an equivalent Windows time zone ID. For example,
1118 * Windows time zone ID "Pacific Standard Time" is returned for input "America/Los_Angeles".
1120 * <p>There are system time zones that cannot be mapped to Windows zones. When the input
1121 * system time zone ID is unknown or unmappable to a Windows time zone, then this
1122 * method returns <code>null</code>.
1124 * <p>This implementation utilizes <a href="http://unicode.org/cldr/charts/supplemental/zone_tzid.html">
1125 * Zone-Tzid mapping data<a>. The mapping data is updated time to time. To get the latest changes,
1126 * please read the ICU user guide section <a href="http://userguide.icu-project.org/datetime/timezone#TOC-Updating-the-Time-Zone-Data">
1127 * Updating the Time Zone Data</a>.
1129 * @param id A system time zone ID
1130 * @return A Windows time zone ID mapped from the input system time zone ID,
1131 * or <code>null</code> when the input ID is unknown or unmappable.
1132 * @see #getIDForWindowsID(String, String)
1135 * @provisional This API might change or be removed in a future release.
1137 public static String getWindowsID(String id) {
1138 // canonicalize the input ID
1139 boolean[] isSystemID = {false};
1140 id = getCanonicalID(id, isSystemID);
1141 if (!isSystemID[0]) {
1142 // mapping data is only applicable to tz database IDs
1146 UResourceBundle top = UResourceBundle.getBundleInstance(
1147 ICUResourceBundle.ICU_BASE_NAME, "windowsZones", ICUResourceBundle.ICU_DATA_CLASS_LOADER);
1148 UResourceBundle mapTimezones = top.get("mapTimezones");
1150 UResourceBundleIterator resitr = mapTimezones.getIterator();
1151 while (resitr.hasNext()) {
1152 UResourceBundle winzone = resitr.next();
1153 if (winzone.getType() != UResourceBundle.TABLE) {
1156 UResourceBundleIterator rgitr = winzone.getIterator();
1157 while (rgitr.hasNext()) {
1158 UResourceBundle regionalData = rgitr.next();
1159 if (regionalData.getType() != UResourceBundle.STRING) {
1162 String[] tzids = regionalData.getString().split(" ");
1163 for (String tzid : tzids) {
1164 if (tzid.equals(id)) {
1165 return winzone.getKey();
1175 * {@icu} Converts a Windows time zone ID to an equivalent system time zone ID
1176 * for a region. For example, system time zone ID "America/Los_Angeles" is returned
1177 * for input Windows ID "Pacific Standard Time" and region "US" (or <code>null</code>),
1178 * "America/Vancouver" is returned for the same Windows ID "Pacific Standard Time" and
1181 * <p>Not all Windows time zones can be mapped to system time zones. When the input
1182 * Windows time zone ID is unknown or unmappable to a system time zone, then this
1183 * method returns <code>null</code>.
1185 * <p>This implementation utilizes <a href="http://unicode.org/cldr/charts/supplemental/zone_tzid.html">
1186 * Zone-Tzid mapping data<a>. The mapping data is updated time to time. To get the latest changes,
1187 * please read the ICU user guide section <a href="http://userguide.icu-project.org/datetime/timezone#TOC-Updating-the-Time-Zone-Data">
1188 * Updating the Time Zone Data</a>.
1190 * @param winid A Windows time zone ID
1191 * @param region A region code, or <code>null</code> if no regional preference.
1192 * @return A system time zone ID mapped from the input Windows time zone ID,
1193 * or <code>null</code> when the input ID is unknown or unmappable.
1194 * @see #getWindowsID(String)
1197 * @provisional This API might change or be removed in a future release.
1199 public static String getIDForWindowsID(String winid, String region) {
1202 UResourceBundle top = UResourceBundle.getBundleInstance(
1203 ICUResourceBundle.ICU_BASE_NAME, "windowsZones", ICUResourceBundle.ICU_DATA_CLASS_LOADER);
1204 UResourceBundle mapTimezones = top.get("mapTimezones");
1207 UResourceBundle zones = mapTimezones.get(winid);
1208 if (region != null) {
1210 id = zones.getString(region);
1212 // first ID delimited by space is the default one
1213 int endIdx = id.indexOf(' ');
1215 id = id.substring(0, endIdx);
1218 } catch (MissingResourceException e) {
1219 // no explicit region mapping found
1223 id = zones.getString("001");
1225 } catch (MissingResourceException e) {
1226 // no mapping data found
1238 public boolean isFrozen() {
1246 public TimeZone freeze() {
1247 throw new UnsupportedOperationException("Needs to be implemented by the subclass.");
1254 public TimeZone cloneAsThawed() {
1256 TimeZone other = (TimeZone) super.clone();
1258 } catch (CloneNotSupportedException e) {
1259 throw new RuntimeException(e);
1263 // =======================privates===============================
1266 * The string identifier of this <code>TimeZone</code>. This is a
1267 * programmatic identifier used internally to look up <code>TimeZone</code>
1268 * objects from the system table and also to map them to their localized
1269 * display names. <code>ID</code> values are unique in the system
1270 * table but may not be for dynamically created zones.
1276 * The default time zone, or null if not set.
1278 private static TimeZone defaultZone = null;
1281 * The tzdata version
1283 private static String TZDATA_VERSION = null;
1286 * TimeZone implementation type
1288 private static int TZ_IMPL = TIMEZONE_ICU;
1291 * TimeZone implementation type initialization
1293 private static final String TZIMPL_CONFIG_KEY = "com.ibm.icu.util.TimeZone.DefaultTimeZoneType";
1294 private static final String TZIMPL_CONFIG_ICU = "ICU";
1295 private static final String TZIMPL_CONFIG_JDK = "JDK";
1298 String type = ICUConfig.get(TZIMPL_CONFIG_KEY, TZIMPL_CONFIG_ICU);
1299 if (type.equalsIgnoreCase(TZIMPL_CONFIG_JDK)) {
1300 TZ_IMPL = TIMEZONE_JDK;