]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_8_1_1/main/classes/core/src/com/ibm/icu/util/TimeZone.java
Added flags.
[Dictionary.git] / jars / icu4j-4_8_1_1 / main / classes / core / src / com / ibm / icu / util / TimeZone.java
1 /*
2  * @(#)TimeZone.java    1.51 00/01/19
3  *
4  * Copyright (C) 1996-2011, International Business Machines
5  * Corporation and others.  All Rights Reserved.
6  */
7
8 package com.ibm.icu.util;
9
10 import java.io.Serializable;
11 import java.util.Date;
12 import java.util.Locale;
13 import java.util.MissingResourceException;
14 import java.util.Set;
15
16 import com.ibm.icu.impl.Grego;
17 import com.ibm.icu.impl.ICUConfig;
18 import com.ibm.icu.impl.ICULogger;
19 import com.ibm.icu.impl.JavaTimeZone;
20 import com.ibm.icu.impl.TimeZoneAdapter;
21 import com.ibm.icu.impl.ZoneMeta;
22 import com.ibm.icu.text.TimeZoneFormat;
23 import com.ibm.icu.text.TimeZoneFormat.Style;
24 import com.ibm.icu.text.TimeZoneFormat.TimeType;
25 import com.ibm.icu.text.TimeZoneNames;
26 import com.ibm.icu.text.TimeZoneNames.NameType;
27 import com.ibm.icu.util.ULocale.Category;
28
29 /**
30  * {@icuenhanced java.util.TimeZone}.{@icu _usage_}
31  *
32  * <p><code>TimeZone</code> represents a time zone offset, and also computes daylight
33  * savings.
34  *
35  * <p>Typically, you get a <code>TimeZone</code> using {@link #getDefault()}
36  * which creates a <code>TimeZone</code> based on the time zone where the program
37  * is running. For example, for a program running in Japan, <code>getDefault</code>
38  * creates a <code>TimeZone</code> object based on Japanese Standard Time.
39  *
40  * <p>You can also get a <code>TimeZone</code> using {@link #getTimeZone(String)}
41  * along with a time zone ID. For instance, the time zone ID for the
42  * U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a
43  * U.S. Pacific Time <code>TimeZone</code> object with:
44  *
45  * <blockquote>
46  * <pre>
47  * TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
48  * </pre>
49  * </blockquote>
50  * You can use the {@link #getAvailableIDs()} method to iterate through
51  * all the supported time zone IDs. You can then choose a
52  * supported ID to get a <code>TimeZone</code>.
53  * If the time zone you want is not represented by one of the
54  * supported IDs, then you can create a custom time zone ID with
55  * the following syntax:
56  *
57  * <blockquote>
58  * <pre>
59  * GMT[+|-]hh[[:]mm]
60  * </pre>
61  * </blockquote>
62  *
63  * For example, you might specify GMT+14:00 as a custom
64  * time zone ID.  The <code>TimeZone</code> that is returned
65  * when you specify a custom time zone ID does not include
66  * daylight savings time.
67  *
68  * <p>For compatibility with JDK 1.1.x, some other three-letter time zone IDs
69  * (such as "PST", "CTT", "AST") are also supported. However, <strong>their
70  * use is deprecated</strong> because the same abbreviation is often used
71  * for multiple time zones (for example, "CST" could be U.S. "Central Standard
72  * Time" and "China Standard Time"), and the Java platform can then only
73  * recognize one of them.
74  *
75  * <p><strong>Note:</strong> Starting from ICU4J 4.0, you can optionally choose
76  * JDK <code>TimeZone</code> as the time zone implementation.  The TimeZone factory
77  * method <code>getTimeZone</code> creates an instance of ICU's own <code>TimeZone</code>
78  * subclass by default.  If you want to use the JDK implementation always, you can
79  * set the default time zone implementation type by the new method
80  * <code>setDefaultTimeZoneType</code>.  Alternatively, you can change the initial
81  * default implementation type by setting a property below.
82  *
83  * <blockquote>
84  * <pre>
85  * #
86  * # The default TimeZone implementation type used by the ICU TimeZone
87  * # factory method. [ ICU | JDK ]
88  * #
89  * com.ibm.icu.util.TimeZone.DefaultTimeZoneType = ICU
90  * </pre>
91  * </blockquote>
92  *
93  * <p>This property is included in ICUConfig.properties in com.ibm.icu package.  When the
94  * <code>TimeZone</code> class is loaded, the initialization code checks if the property
95  * <code>com.ibm.icu.util.TimeZone.DefaultTimeZoneType=xxx</code> is defined by the system
96  * properties.  If not available, then it loads ICUConfig.properties to get the default
97  * time zone implementation type.  The property setting is only used for the initial
98  * default value and you can change the default type by calling
99  * <code>setDefaultTimeZoneType</code> at runtime.
100  *
101  * @see          Calendar
102  * @see          GregorianCalendar
103  * @see          SimpleTimeZone
104  * @author       Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
105  * @stable ICU 2.0
106  */
107 abstract public class TimeZone implements Serializable, Cloneable {
108     /**
109      * {@icu} A logger for TimeZone. Will be null if logging is not on by way of system
110      * property: "icu4j.debug.logging"
111      * @draft ICU 4.4
112      * @provisional This API might change or be removed in a future release.
113      */
114     public static ICULogger TimeZoneLogger = ICULogger.getICULogger(TimeZone.class.getName());
115
116     // using serialver from jdk1.4.2_05
117     private static final long serialVersionUID = -744942128318337471L;
118
119     /**
120      * Default constructor.  (For invocation by subclass constructors,
121      * typically implicit.)
122      * @stable ICU 2.8
123      */
124     public TimeZone() {
125     }
126
127     /**
128      * {@icu} A time zone implementation type indicating ICU's own TimeZone used by
129      * <code>getTimeZone</code>, <code>setDefaultTimeZoneType</code>
130      * and <code>getDefaultTimeZoneType</code>.
131      * @stable ICU 4.0
132      */
133     public static final int TIMEZONE_ICU = 0;
134     /**
135      * {@icu} A time zone implementation type indicating JDK TimeZone used by
136      * <code>getTimeZone</code>, <code>setDefaultTimeZoneType</code>
137      * and <code>getDefaultTimeZoneType</code>.
138      * @stable ICU 4.0
139      */
140     public static final int TIMEZONE_JDK = 1;
141
142     /**
143      * A style specifier for <code>getDisplayName()</code> indicating
144      * a short name, such as "PST."
145      * @see #LONG
146      * @stable ICU 2.0
147      */
148     public static final int SHORT = 0;
149
150     /**
151      * A style specifier for <code>getDisplayName()</code> indicating
152      * a long name, such as "Pacific Standard Time."
153      * @see #SHORT
154      * @stable ICU 2.0
155      */
156     public static final int LONG  = 1;
157
158     /**
159      * {@icu} A style specifier for <code>getDisplayName()</code> indicating
160      * a short generic name, such as "PT."
161      * @see #LONG_GENERIC
162      * @stable ICU 4.4
163      */
164     public static final int SHORT_GENERIC = 2;
165
166     /**
167      * {@icu} A style specifier for <code>getDisplayName()</code> indicating
168      * a long generic name, such as "Pacific Time."
169      * @see #SHORT_GENERIC
170      * @stable ICU 4.4
171      */
172     public static final int LONG_GENERIC = 3;
173
174     /**
175      * {@icu} A style specifier for <code>getDisplayName()</code> indicating
176      * a short name derived from the timezone's offset, such as "-0800."
177      * @see #LONG_GMT
178      * @stable ICU 4.4
179      */
180     public static final int SHORT_GMT = 4;
181
182     /**
183      * {@icu} A style specifier for <code>getDisplayName()</code> indicating
184      * a long name derived from the timezone's offset, such as "GMT-08:00."
185      * @see #SHORT_GMT
186      * @stable ICU 4.4
187      */
188     public static final int LONG_GMT = 5;
189
190     /**
191      * {@icu} A style specifier for <code>getDisplayName()</code> indicating
192      * a short name derived from the timezone's short standard or daylight
193      * timezone name ignoring commonlyUsed, such as "PDT."
194      * @stable ICU 4.4
195      */
196
197     public static final int SHORT_COMMONLY_USED = 6;
198
199     /**
200      * {@icu} A style specifier for <code>getDisplayName()</code> indicating
201      * a long name derived from the timezone's fallback name, such as
202      * "United States (Los Angeles)."
203      * @stable ICU 4.4
204      */
205     public static final int GENERIC_LOCATION = 7;
206
207     /**
208      * {@icu} The time zone ID reserved for unknown time zone.
209      * @see #getTimeZone(String)
210      * 
211      * @draft ICU 4.8
212      * @provisional This API might change or be removed in a future release.
213      */
214     public static final String UNKNOWN_ZONE_ID = "Etc/Unknown";
215
216     /**
217      * {@icu} System time zone type constants used by filtering zones in
218      * {@link TimeZone#getAvailableIDs(SystemTimeZoneType, String, Integer)}
219      *
220      * @draft ICU 4.8
221      * @provisional This API might change or be removed in a future release.
222      */
223     public enum SystemTimeZoneType {
224         /**
225          * Any system zones.
226          * @draft ICU 4.8
227          * @provisional This API might change or be removed in a future release.
228          */
229         ANY,
230
231         /**
232          * Canonical system zones.
233          * @draft ICU 4.8
234          * @provisional This API might change or be removed in a future release.
235          */
236         CANONICAL,
237
238         /**
239          * Canonical system zones associated with actual locations.
240          * @draft ICU 4.8
241          * @provisional This API might change or be removed in a future release.
242          */
243         CANONICAL_LOCATION,
244     }
245
246     /**
247      * Gets the time zone offset, for current date, modified in case of
248      * daylight savings. This is the offset to add *to* UTC to get local time.
249      * @param era the era of the given date.
250      * @param year the year in the given date.
251      * @param month the month in the given date.
252      * Month is 0-based. e.g., 0 for January.
253      * @param day the day-in-month of the given date.
254      * @param dayOfWeek the day-of-week of the given date.
255      * @param milliseconds the millis in day in <em>standard</em> local time.
256      * @return the offset to add *to* GMT to get local time.
257      * @stable ICU 2.0
258      */
259     abstract public int getOffset(int era, int year, int month, int day,
260                                   int dayOfWeek, int milliseconds);
261
262
263     /**
264      * Returns the offset of this time zone from UTC at the specified
265      * date. If Daylight Saving Time is in effect at the specified
266      * date, the offset value is adjusted with the amount of daylight
267      * saving.
268      *
269      * @param date the date represented in milliseconds since January 1, 1970 00:00:00 GMT
270      * @return the amount of time in milliseconds to add to UTC to get local time.
271      *
272      * @see Calendar#ZONE_OFFSET
273      * @see Calendar#DST_OFFSET
274      * @see #getOffset(long, boolean, int[])
275      * @stable ICU 2.8
276      */
277     public int getOffset(long date) {
278         int[] result = new int[2];
279         getOffset(date, false, result);
280         return result[0]+result[1];
281     }
282
283     /**
284      * Returns the time zone raw and GMT offset for the given moment
285      * in time.  Upon return, local-millis = GMT-millis + rawOffset +
286      * dstOffset.  All computations are performed in the proleptic
287      * Gregorian calendar.  The default implementation in the TimeZone
288      * class delegates to the 8-argument getOffset().
289      *
290      * @param date moment in time for which to return offsets, in
291      * units of milliseconds from January 1, 1970 0:00 GMT, either GMT
292      * time or local wall time, depending on `local'.
293      * @param local if true, `date' is local wall time; otherwise it
294      * is in GMT time.
295      * @param offsets output parameter to receive the raw offset, that
296      * is, the offset not including DST adjustments, in offsets[0],
297      * and the DST offset, that is, the offset to be added to
298      * `rawOffset' to obtain the total offset between local and GMT
299      * time, in offsets[1]. If DST is not in effect, the DST offset is
300      * zero; otherwise it is a positive value, typically one hour.
301      *
302      * @stable ICU 2.8
303      */
304     public void getOffset(long date, boolean local, int[] offsets) {
305         offsets[0] = getRawOffset();
306         if (!local) {
307             date += offsets[0]; // now in local standard millis
308         }
309
310         // When local == true, date might not be in local standard
311         // millis.  getOffset taking 6 parameters used here assume
312         // the given time in day is local standard time.
313         // At STD->DST transition, there is a range of time which
314         // does not exist.  When 'date' is in this time range
315         // (and local == true), this method interprets the specified
316         // local time as DST.  At DST->STD transition, there is a
317         // range of time which occurs twice.  In this case, this
318         // method interprets the specified local time as STD.
319         // To support the behavior above, we need to call getOffset
320         // (with 6 args) twice when local == true and DST is
321         // detected in the initial call.
322         int fields[] = new int[6];
323         for (int pass = 0; ; pass++) {
324             Grego.timeToFields(date, fields);
325             offsets[1] = getOffset(GregorianCalendar.AD,
326                                     fields[0], fields[1], fields[2],
327                                     fields[3], fields[5]) - offsets[0];
328
329             if (pass != 0 || !local || offsets[1] == 0) {
330                 break;
331             }
332             // adjust to local standard millis
333             date -= offsets[1];
334         }
335     }
336
337     /**
338      * Sets the base time zone offset to GMT.
339      * This is the offset to add *to* UTC to get local time.
340      * @param offsetMillis the given base time zone offset to GMT.
341      * @stable ICU 2.0
342      */
343     abstract public void setRawOffset(int offsetMillis);
344
345     /**
346      * Gets unmodified offset, NOT modified in case of daylight savings.
347      * This is the offset to add *to* UTC to get local time.
348      * @return the unmodified offset to add *to* UTC to get local time.
349      * @stable ICU 2.0
350      */
351     abstract public int getRawOffset();
352
353     /**
354      * Gets the ID of this time zone.
355      * @return the ID of this time zone.
356      * @stable ICU 2.0
357      */
358     public String getID() {
359         return ID;
360     }
361
362     /**
363      * Sets the time zone ID. This does not change any other data in
364      * the time zone object.
365      * @param ID the new time zone ID.
366      * @stable ICU 2.0
367      */
368     public void setID(String ID) {
369         if (ID == null) {
370             throw new NullPointerException();
371         }
372         this.ID = ID;
373     }
374
375     /**
376      * Returns a name of this time zone suitable for presentation to the user
377      * in the default <code>DISPLAY</code> locale.
378      * This method returns the long generic name.
379      * If the display name is not available for the locale,
380      * a fallback based on the country, city, or time zone id will be used.
381      * @return the human-readable name of this time zone in the default locale.
382      * @see Category#DISPLAY
383      * @stable ICU 2.0
384      */
385     public final String getDisplayName() {
386         return _getDisplayName(LONG_GENERIC, false, ULocale.getDefault(Category.DISPLAY));
387     }
388
389     /**
390      * Returns a name of this time zone suitable for presentation to the user
391      * in the specified locale.
392      * This method returns the long generic name.
393      * If the display name is not available for the locale,
394      * a fallback based on the country, city, or time zone id will be used.
395      * @param locale the locale in which to supply the display name.
396      * @return the human-readable name of this time zone in the given locale
397      * or in the default locale if the given locale is not recognized.
398      * @stable ICU 2.0
399      */
400     public final String getDisplayName(Locale locale) {
401         return _getDisplayName(LONG_GENERIC, false, ULocale.forLocale(locale));
402     }
403
404     /**
405      * Returns a name of this time zone suitable for presentation to the user
406      * in the specified locale.
407      * This method returns the long name, not including daylight savings.
408      * If the display name is not available for the locale,
409      * a fallback based on the country, city, or time zone id will be used.
410      * @param locale the ulocale in which to supply the display name.
411      * @return the human-readable name of this time zone in the given locale
412      * or in the default ulocale if the given ulocale is not recognized.
413      * @stable ICU 3.2
414      */
415     public final String getDisplayName(ULocale locale) {
416         return _getDisplayName(LONG_GENERIC, false, locale);
417     }
418
419     /**
420      * Returns a name of this time zone suitable for presentation to the user
421      * in the default <code>DISPLAY</code> locale.
422      * If the display name is not available for the locale,
423      * then this method returns a string in the localized GMT offset format
424      * such as <code>GMT[+-]HH:mm</code>.
425      * @param daylight if true, return the daylight savings name.
426      * @param style the output style of the display name.  Valid styles are
427      * <code>SHORT</code>, <code>LONG</code>, <code>SHORT_GENERIC</code>,
428      * <code>LONG_GENERIC</code>, <code>SHORT_GMT</code>, <code>LONG_GMT</code>,
429      * <code>SHORT_COMMONLY_USED</code> or <code>GENERIC_LOCATION</code>.
430      * @return the human-readable name of this time zone in the default locale.
431      * @see Category#DISPLAY
432      * @stable ICU 2.0
433      */
434     public final String getDisplayName(boolean daylight, int style) {
435         return getDisplayName(daylight, style, ULocale.getDefault(Category.DISPLAY));
436     }
437
438     /**
439      * Returns a name of this time zone suitable for presentation to the user
440      * in the specified locale.
441      * If the display name is not available for the locale,
442      * then this method returns a string in the localized GMT offset format
443      * such as <code>GMT[+-]HH:mm</code>.
444      * @param daylight if true, return the daylight savings name.
445      * @param style the output style of the display name.  Valid styles are
446      * <code>SHORT</code>, <code>LONG</code>, <code>SHORT_GENERIC</code>,
447      * <code>LONG_GENERIC</code>, <code>SHORT_GMT</code>, <code>LONG_GMT</code>,
448      * <code>SHORT_COMMONLY_USED</code> or <code>GENERIC_LOCATION</code>.
449      * @param locale the locale in which to supply the display name.
450      * @return the human-readable name of this time zone in the given locale
451      * or in the default locale if the given locale is not recognized.
452      * @exception IllegalArgumentException style is invalid.
453      * @stable ICU 2.0
454      */
455     public String getDisplayName(boolean daylight, int style, Locale locale) {
456         return getDisplayName(daylight, style, ULocale.forLocale(locale));
457     }
458
459     /**
460      * Returns a name of this time zone suitable for presentation to the user
461      * in the specified locale.
462      * If the display name is not available for the locale,
463      * then this method returns a string in the localized GMT offset format
464      * such as <code>GMT[+-]HH:mm</code>.
465      * @param daylight if true, return the daylight savings name.
466      * @param style the output style of the display name.  Valid styles are
467      * <code>SHORT</code>, <code>LONG</code>, <code>SHORT_GENERIC</code>,
468      * <code>LONG_GENERIC</code>, <code>SHORT_GMT</code>, <code>LONG_GMT</code>,
469      * <code>SHORT_COMMONLY_USED</code> or <code>GENERIC_LOCATION</code>.
470      * @param locale the locale in which to supply the display name.
471      * @return the human-readable name of this time zone in the given locale
472      * or in the default locale if the given locale is not recognized.
473      * @exception IllegalArgumentException style is invalid.
474      * @stable ICU 3.2
475      */
476     public String getDisplayName(boolean daylight, int style, ULocale locale) {
477         if (style < SHORT || style > GENERIC_LOCATION) {
478             throw new IllegalArgumentException("Illegal style: " + style);
479         }
480         
481         return _getDisplayName(style, daylight, locale);
482     }
483
484     /**
485      * internal version (which is called by public APIs) accepts
486      * SHORT, LONG, SHORT_GENERIC, LONG_GENERIC, SHORT_GMT, LONG_GMT,
487      * SHORT_COMMONLY_USED and GENERIC_LOCATION.
488      */
489     private String _getDisplayName(int style, boolean daylight, ULocale locale) {
490         if (locale == null) {
491             throw new NullPointerException("locale is null");
492         }
493
494         String result = null;
495
496         if (style == GENERIC_LOCATION || style == LONG_GENERIC || style == SHORT_GENERIC) {
497             // Generic format
498             TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(locale);
499             long date = System.currentTimeMillis();
500             Output<TimeType> timeType = new Output<TimeType>(TimeType.UNKNOWN);
501
502             switch (style) {
503             case GENERIC_LOCATION:
504                 result = tzfmt.format(Style.GENERIC_LOCATION, this, date, timeType);
505                 break;
506             case LONG_GENERIC:
507                 result = tzfmt.format(Style.GENERIC_LONG, this, date, timeType);
508                 break;
509             case SHORT_GENERIC:
510                 result = tzfmt.format(Style.GENERIC_SHORT, this, date, timeType);
511                 break;
512             }
513
514             // Generic format many use Localized GMT as the final fallback.
515             // When Localized GMT format is used, the result might not be
516             // appropriate for the requested daylight value.
517             if (daylight && timeType.value == TimeType.STANDARD ||
518                     !daylight && timeType.value == TimeType.DAYLIGHT) {
519                 int offset = daylight ? getRawOffset() + getDSTSavings() : getRawOffset();
520                 result = tzfmt.formatOffsetLocalizedGMT(offset);
521             }
522
523         } else if (style == LONG_GMT || style == SHORT_GMT) {
524             // Offset format
525             TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(locale);
526             int offset = daylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
527             switch (style) {
528             case LONG_GMT:
529                 result = tzfmt.formatOffsetLocalizedGMT(offset);
530                 break;
531             case SHORT_GMT:
532                 result = tzfmt.formatOffsetRFC822(offset);
533                 break;
534             }
535         } else {
536             // Specific format
537             assert(style == LONG || style == SHORT || style == SHORT_COMMONLY_USED);
538
539             // Gets the name directly from TimeZoneNames
540             long date = System.currentTimeMillis();
541             TimeZoneNames tznames = TimeZoneNames.getInstance(locale);
542             NameType nameType = null;
543             switch (style) {
544             case LONG:
545                 nameType = daylight ? NameType.LONG_DAYLIGHT : NameType.LONG_STANDARD;
546                 break;
547             case SHORT:
548                 nameType = daylight ? NameType.SHORT_DAYLIGHT : NameType.SHORT_STANDARD;
549                 break;
550             case SHORT_COMMONLY_USED:
551                 nameType = daylight ? NameType.SHORT_DAYLIGHT_COMMONLY_USED : NameType.SHORT_STANDARD_COMMONLY_USED;
552                 break;
553             }
554             result = tznames.getDisplayName(ZoneMeta.getCanonicalCLDRID(this), nameType, date);
555             if (result == null) {
556                 // Fallback to localized GMT
557                 TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(locale);
558                 int offset = daylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
559                 result = tzfmt.formatOffsetLocalizedGMT(offset);
560             }
561         }
562         assert(result != null);
563
564         return result;
565     }
566
567     /**
568      * Returns the amount of time to be added to local standard time
569      * to get local wall clock time.
570      * <p>
571      * The default implementation always returns 3600000 milliseconds
572      * (i.e., one hour) if this time zone observes Daylight Saving
573      * Time. Otherwise, 0 (zero) is returned.
574      * <p>
575      * If an underlying TimeZone implementation subclass supports
576      * historical Daylight Saving Time changes, this method returns
577      * the known latest daylight saving value.
578      *
579      * @return the amount of saving time in milliseconds
580      * @stable ICU 2.8
581      */
582     public int getDSTSavings() {
583         if (useDaylightTime()) {
584             return 3600000;
585         }
586         return 0;
587     }
588
589     /**
590      * Queries if this time zone uses daylight savings time.
591      * @return true if this time zone uses daylight savings time,
592      * false, otherwise.
593      * <p><strong>Note:</strong>The default implementation of
594      * ICU TimeZone uses the tz database, which supports historic
595      * rule changes, for system time zones. With the implementation,
596      * there are time zones that used daylight savings time in the
597      * past, but no longer used currently. For example, Asia/Tokyo has
598      * never used daylight savings time since 1951. Most clients would
599      * expect that this method to return <code>false</code> for such case.
600      * The default implementation of this method returns <code>true</code>
601      * when the time zone uses daylight savings time in the current
602      * (Gregorian) calendar year.
603      * @stable ICU 2.0
604      */
605     abstract public boolean useDaylightTime();
606
607     /**
608      * Queries if the given date is in daylight savings time in
609      * this time zone.
610      * @param date the given Date.
611      * @return true if the given date is in daylight savings time,
612      * false, otherwise.
613      * @stable ICU 2.0
614      */
615     abstract public boolean inDaylightTime(Date date);
616
617     /**
618      * Gets the <code>TimeZone</code> for the given ID.
619      *
620      * @param ID the ID for a <code>TimeZone</code>, such as "America/Los_Angeles",
621      * or a custom ID such as "GMT-8:00". Note that the support of abbreviations,
622      * such as "PST", is for JDK 1.1.x compatibility only and full names should be used.
623      *
624      * @return the specified <code>TimeZone</code>, or the GMT zone with ID "Etc/Unknown"
625      * if the given ID cannot be understood.
626      * @see #UNKNOWN_ZONE_ID
627      * @stable ICU 2.0
628      */
629     public static synchronized TimeZone getTimeZone(String ID) {
630         return getTimeZone(ID, TZ_IMPL);
631     }
632
633     /**
634      * Gets the <code>TimeZone</code> for the given ID and the timezone type.
635      * @param ID the ID for a <code>TimeZone</code>, such as "America/Los_Angeles", or a
636      * custom ID such as "GMT-8:00". Note that the support of abbreviations, such as
637      * "PST", is for JDK 1.1.x compatibility only and full names should be used.
638      * @param type Time zone type, either <code>TIMEZONE_ICU</code> or
639      * <code>TIMEZONE_JDK</code>.
640      * @return the specified <code>TimeZone</code>, or the GMT zone if the given ID
641      * cannot be understood.
642      * @stable ICU 4.0
643      */
644     public static synchronized TimeZone getTimeZone(String ID, int type) {
645         TimeZone result;
646         if (type == TIMEZONE_JDK) {
647             result = new JavaTimeZone(ID);
648         } else {
649             /* We first try to lookup the zone ID in our system list.  If this
650              * fails, we try to parse it as a custom string GMT[+-]HH:mm.  If
651              * all else fails, we return GMT, which is probably not what the
652              * user wants, but at least is a functioning TimeZone object.
653              *
654              * We cannot return NULL, because that would break compatibility
655              * with the JDK.
656              */
657             if(ID==null){
658                 throw new NullPointerException();
659             }
660             result = ZoneMeta.getSystemTimeZone(ID);
661
662             if (result == null) {
663                 result = ZoneMeta.getCustomTimeZone(ID);
664             }
665             if (result == null) {
666                 /* Log that timezone is using GMT if logging is on. */
667                 if (TimeZoneLogger != null && TimeZoneLogger.isLoggingOn()) {
668                     TimeZoneLogger.warning(
669                         "\"" +ID + "\" is a bogus id so timezone is falling back to Etc/Unknown(GMT).");
670                 }
671                 result = new SimpleTimeZone(0, UNKNOWN_ZONE_ID);
672             }
673         }
674         return result;
675     }
676
677     /**
678      * Sets the default time zone type used by <code>getTimeZone</code>.
679      * @param type time zone type, either <code>TIMEZONE_ICU</code> or
680      * <code>TIMEZONE_JDK</code>.
681      * @stable ICU 4.0
682      */
683     public static synchronized void setDefaultTimeZoneType(int type) {
684         if (type != TIMEZONE_ICU && type != TIMEZONE_JDK) {
685             throw new IllegalArgumentException("Invalid timezone type");
686         }
687         TZ_IMPL = type;
688     }
689
690     /**
691      * {@icu} Returns the default time zone type currently used.
692      * @return The default time zone type, either <code>TIMEZONE_ICU</code> or
693      * <code>TIMEZONE_JDK</code>.
694      * @stable ICU 4.0
695      */
696     public static int getDefaultTimeZoneType() {
697         return TZ_IMPL;
698     }
699
700     /** 
701      * {@icu} Returns a set of time zone ID strings with the given filter conditions. 
702      * <p><b>Note:</b>A <code>Set</code> returned by this method is
703      * immutable.
704      * @param zoneType      The system time zone type.
705      * @param region        The ISO 3166 two-letter country code or UN M.49 three-digit area code. 
706      *                      When null, no filtering done by region. 
707      * @param rawOffset     An offset from GMT in milliseconds, ignoring the effect of daylight savings 
708      *                      time, if any. When null, no filtering done by zone offset. 
709      * @return an immutable set of system time zone IDs.
710      * @see SystemTimeZoneType
711      * 
712      * @draft ICU 4.8
713      * @provisional This API might change or be removed in a future release.
714      */ 
715     public static Set<String> getAvailableIDs(SystemTimeZoneType zoneType,
716             String region, Integer rawOffset) {
717         return ZoneMeta.getAvailableIDs(zoneType, region, rawOffset);
718     }
719
720     /**
721      * Return a new String array containing all system TimeZone IDs
722      * with the given raw offset from GMT.  These IDs may be passed to
723      * <code>get()</code> to construct the corresponding TimeZone
724      * object.
725      * @param rawOffset the offset in milliseconds from GMT
726      * @return an array of IDs for system TimeZones with the given
727      * raw offset.  If there are none, return a zero-length array.
728      * @see #getAvailableIDs(SystemTimeZoneType, String, Integer)
729      * 
730      * @stable ICU 2.0
731      */
732     public static String[] getAvailableIDs(int rawOffset) {
733         Set<String> ids = getAvailableIDs(SystemTimeZoneType.ANY, null, Integer.valueOf(rawOffset));
734         return ids.toArray(new String[0]);
735     }
736
737     /**
738      * Return a new String array containing all system TimeZone IDs
739      * associated with the given country.  These IDs may be passed to
740      * <code>get()</code> to construct the corresponding TimeZone
741      * object.
742      * @param country a two-letter ISO 3166 country code, or <code>null</code>
743      * to return zones not associated with any country
744      * @return an array of IDs for system TimeZones in the given
745      * country.  If there are none, return a zero-length array.
746      * @see #getAvailableIDs(SystemTimeZoneType, String, Integer)
747      * 
748      * @stable ICU 2.0
749      */
750     public static String[] getAvailableIDs(String country) {
751         Set<String> ids = getAvailableIDs(SystemTimeZoneType.ANY, country, null);
752         return ids.toArray(new String[0]);
753     }
754
755     /**
756      * Return a new String array containing all system TimeZone IDs.
757      * These IDs (and only these IDs) may be passed to
758      * <code>get()</code> to construct the corresponding TimeZone
759      * object.
760      * @return an array of all system TimeZone IDs
761      * @see #getAvailableIDs(SystemTimeZoneType, String, Integer)
762      * 
763      * @stable ICU 2.0
764      */
765     public static String[] getAvailableIDs() {
766         Set<String> ids = getAvailableIDs(SystemTimeZoneType.ANY, null, null);
767         return ids.toArray(new String[0]);
768     }
769
770     /**
771      * {@icu} Returns the number of IDs in the equivalency group that
772      * includes the given ID.  An equivalency group contains zones
773      * that have the same GMT offset and rules.
774      *
775      * <p>The returned count includes the given ID; it is always >= 1
776      * for valid IDs.  The given ID must be a system time zone.  If it
777      * is not, returns zero.
778      * @param id a system time zone ID
779      * @return the number of zones in the equivalency group containing
780      * 'id', or zero if 'id' is not a valid system ID
781      * @see #getEquivalentID
782      * @stable ICU 2.0
783      */
784     public static int countEquivalentIDs(String id) {
785         return ZoneMeta.countEquivalentIDs(id);
786     }
787
788     /**
789      * Returns an ID in the equivalency group that
790      * includes the given ID.  An equivalency group contains zones
791      * that have the same GMT offset and rules.
792      *
793      * <p>The given index must be in the range 0..n-1, where n is the
794      * value returned by <code>countEquivalentIDs(id)</code>.  For
795      * some value of 'index', the returned value will be equal to the
796      * given id.  If the given id is not a valid system time zone, or
797      * if 'index' is out of range, then returns an empty string.
798      * @param id a system time zone ID
799      * @param index a value from 0 to n-1, where n is the value
800      * returned by <code>countEquivalentIDs(id)</code>
801      * @return the ID of the index-th zone in the equivalency group
802      * containing 'id', or an empty string if 'id' is not a valid
803      * system ID or 'index' is out of range
804      * @see #countEquivalentIDs
805      * @stable ICU 2.0
806      */
807     public static String getEquivalentID(String id, int index) {
808         return ZoneMeta.getEquivalentID(id, index);
809     }
810
811     /**
812      * Gets the default <code>TimeZone</code> for this host.
813      * The source of the default <code>TimeZone</code>
814      * may vary with implementation.
815      * @return a default <code>TimeZone</code>.
816      * @stable ICU 2.0
817      */
818     public static synchronized TimeZone getDefault() {
819         if (defaultZone == null) {
820             if (TZ_IMPL == TIMEZONE_JDK) {
821                 defaultZone = new JavaTimeZone();
822             } else {
823                 java.util.TimeZone temp = java.util.TimeZone.getDefault();
824                 defaultZone = getTimeZone(temp.getID());
825             }
826         }
827         return (TimeZone) defaultZone.clone();
828     }
829
830     /**
831      * Sets the <code>TimeZone</code> that is
832      * returned by the <code>getDefault</code> method.  If <code>zone</code>
833      * is null, reset the default to the value it had originally when the
834      * VM first started.
835      * @param tz the new default time zone
836      * @stable ICU 2.0
837      */
838     public static synchronized void setDefault(TimeZone tz) {
839         defaultZone = tz;
840         java.util.TimeZone jdkZone = null;
841         if (defaultZone instanceof JavaTimeZone) {
842             jdkZone = ((JavaTimeZone)defaultZone).unwrap();
843         } else {
844             // Keep java.util.TimeZone default in sync so java.util.Date
845             // can interoperate with com.ibm.icu.util classes.
846
847             if (tz != null) {
848                 if (tz instanceof com.ibm.icu.impl.OlsonTimeZone) {
849                     // Because of the lack of APIs supporting historic
850                     // zone offset/dst saving in JDK TimeZone,
851                     // wrapping ICU TimeZone with JDK TimeZone will
852                     // cause historic offset calculation in Calendar/Date.
853                     // JDK calendar implementation calls getRawOffset() and
854                     // getDSTSavings() when the instance of JDK TimeZone
855                     // is not an instance of JDK internal TimeZone subclass
856                     // (sun.util.calendar.ZoneInfo).  Ticket#6459
857                     String icuID = tz.getID();
858                     jdkZone = java.util.TimeZone.getTimeZone(icuID);
859                     if (!icuID.equals(jdkZone.getID())) {
860                         // JDK does not know the ID..
861                         jdkZone = null;
862                     }
863                 }
864                 if (jdkZone == null) {
865                     jdkZone = TimeZoneAdapter.wrap(tz);
866                 }
867             }
868         }
869         java.util.TimeZone.setDefault(jdkZone);
870     }
871
872     /**
873      * Returns true if this zone has the same rule and offset as another zone.
874      * That is, if this zone differs only in ID, if at all.  Returns false
875      * if the other zone is null.
876      * @param other the <code>TimeZone</code> object to be compared with
877      * @return true if the other zone is not null and is the same as this one,
878      * with the possible exception of the ID
879      * @stable ICU 2.0
880      */
881     public boolean hasSameRules(TimeZone other) {
882         return other != null &&
883             getRawOffset() == other.getRawOffset() &&
884             useDaylightTime() == other.useDaylightTime();
885     }
886
887     /**
888      * Overrides clone.
889      * @stable ICU 2.0
890      */
891     public Object clone() {
892         try {
893             TimeZone other = (TimeZone) super.clone();
894             other.ID = ID;
895             return other;
896         } catch (CloneNotSupportedException e) {
897             throw new IllegalStateException();
898         }
899     }
900
901     /**
902      * Overrides equals.
903      * @stable ICU 3.6
904      */
905     public boolean equals(Object obj){
906         if (this == obj) return true;
907         if (obj == null || getClass() != obj.getClass()) return false;
908         return (ID.equals(((TimeZone)obj).ID));
909     }
910
911     /**
912      * Overrides hashCode.
913      * @stable ICU 3.6
914      */
915     public int hashCode(){
916         return ID.hashCode();
917     }
918
919     /**
920      * {@icu} Returns the time zone data version currently used by ICU.
921      *
922      * @return the version string, such as "2007f"
923      * @throws MissingResourceException if ICU time zone resource bundle
924      * is missing or the version information is not available.
925      *
926      * @stable ICU 3.8
927      */
928     public static synchronized String getTZDataVersion() {
929         if (TZDATA_VERSION == null) {
930             UResourceBundle tzbundle = UResourceBundle.getBundleInstance(
931                     "com/ibm/icu/impl/data/icudt" + VersionInfo.ICU_DATA_VERSION_PATH, "zoneinfo64");
932             TZDATA_VERSION = tzbundle.getString("TZVersion");
933         }
934         return TZDATA_VERSION;
935     }
936
937     /**
938      * {@icu} Returns the canonical system time zone ID or the normalized
939      * custom time zone ID for the given time zone ID.
940      * @param id The input time zone ID to be canonicalized.
941      * @return The canonical system time zone ID or the custom time zone ID
942      * in normalized format for the given time zone ID.  When the given time zone ID
943      * is neither a known system time zone ID nor a valid custom time zone ID,
944      * null is returned.
945      * @stable ICU 4.0
946      */
947     public static String getCanonicalID(String id) {
948         return getCanonicalID(id, null);
949     }
950
951     /**
952      * {@icu} Returns the canonical system time zone ID or the normalized
953      * custom time zone ID for the given time zone ID.
954      * @param id The input time zone ID to be canonicalized.
955      * @param isSystemID When non-null boolean array is specified and
956      * the given ID is a known system time zone ID, true is set to <code>isSystemID[0]</code>
957      * @return The canonical system time zone ID or the custom time zone ID
958      * in normalized format for the given time zone ID.  When the given time zone ID
959      * is neither a known system time zone ID nor a valid custom time zone ID,
960      * null is returned.
961      * @stable ICU 4.0
962      */
963     public static String getCanonicalID(String id, boolean[] isSystemID) {
964         String canonicalID = null;
965         boolean systemTzid = false;
966         if (id != null && id.length() != 0) {
967             if (id.equals(TimeZone.UNKNOWN_ZONE_ID)) {
968                 // special case - Etc/Unknown is a canonical ID, but not system ID
969                 canonicalID = TimeZone.UNKNOWN_ZONE_ID;
970                 systemTzid = false;
971             } else {
972                 canonicalID = ZoneMeta.getCanonicalCLDRID(id);
973                 if (canonicalID != null) {
974                     systemTzid = true;
975                 } else {
976                     canonicalID = ZoneMeta.getCustomID(id);
977                 }
978             }
979         }
980         if (isSystemID != null) {
981             isSystemID[0] = systemTzid;
982         }
983         return canonicalID;
984     }
985
986     /** 
987      * {@icu} Returns the region code associated with the given 
988      * system time zone ID. The region code is either ISO 3166 
989      * 2-letter country code or UN M.49 3-digit area code. 
990      * When the time zone is not associated with a specific location, 
991      * for example - "Etc/UTC", "EST5EDT", then this method returns 
992      * "001" (UN M.49 area code for World). 
993      * @param id the system time zone ID. 
994      * @return the region code associated with the given 
995      * system time zone ID. 
996      * @throws IllegalArgumentException if <code>id</code> is not a known system ID. 
997      * @see #getAvailableIDs(String) 
998      * 
999      * @draft ICU 4.8
1000      * @provisional This API might change or be removed in a future release.
1001      */ 
1002     public static String getRegion(String id) {
1003         String region = null;
1004         // "Etc/Unknown" is not a system time zone ID,
1005         // but in the zone data.
1006         if (!id.equals(UNKNOWN_ZONE_ID)) {
1007             region = ZoneMeta.getRegion(id);
1008         }
1009         if (region == null) {
1010             // unknown id
1011             throw new IllegalArgumentException("Unknown system zone id: " + id);
1012         }
1013         return region;
1014     }
1015
1016     // =======================privates===============================
1017
1018     /**
1019      * The string identifier of this <code>TimeZone</code>.  This is a
1020      * programmatic identifier used internally to look up <code>TimeZone</code>
1021      * objects from the system table and also to map them to their localized
1022      * display names.  <code>ID</code> values are unique in the system
1023      * table but may not be for dynamically created zones.
1024      * @serial
1025      */
1026     private String           ID;
1027
1028     /**
1029      * The default time zone, or null if not set.
1030      */
1031     private static TimeZone  defaultZone = null;
1032
1033     /**
1034      * The tzdata version
1035      */
1036     private static String TZDATA_VERSION = null;
1037
1038     /**
1039      * TimeZone implementation type
1040      */
1041     private static int TZ_IMPL = TIMEZONE_ICU;
1042
1043     /**
1044      * TimeZone implementation type initialization
1045      */
1046     private static final String TZIMPL_CONFIG_KEY = "com.ibm.icu.util.TimeZone.DefaultTimeZoneType";
1047     private static final String TZIMPL_CONFIG_ICU = "ICU";
1048     private static final String TZIMPL_CONFIG_JDK = "JDK";
1049
1050     static {
1051         String type = ICUConfig.get(TZIMPL_CONFIG_KEY, TZIMPL_CONFIG_ICU);
1052         if (type.equalsIgnoreCase(TZIMPL_CONFIG_JDK)) {
1053             TZ_IMPL = TIMEZONE_JDK;
1054         }
1055     }
1056 }
1057
1058 //eof