1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 /*
28  * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
29  * (C) Copyright IBM Corp. 1996 - All Rights Reserved
30  *
31  *   The original version of this source code and documentation is copyrighted
32  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
33  * materials are provided under terms of a License Agreement between Taligent
34  * and Sun. This technology is protected by multiple US and International
35  * patents. This notice and attribution to Taligent may not be removed.
36  *   Taligent is a registered trademark of Taligent, Inc.
37  *
38  */
39 
40 package java.util;
41 
42 import java.io.IOException;
43 import java.io.Serializable;
44 import java.time.ZoneId;
45 import java.util.regex.Matcher;
46 import java.util.regex.Pattern;
47 import java.lang.ref.SoftReference;
48 import java.security.AccessController;
49 import java.security.PrivilegedAction;
50 import java.util.concurrent.ConcurrentHashMap;
51 import libcore.icu.TimeZoneNames;
52 import libcore.io.IoUtils;
53 import libcore.util.ZoneInfoDB;
54 import sun.security.action.GetPropertyAction;
55 import org.apache.harmony.luni.internal.util.TimezoneGetter;
56 
57 /**
58  * <code>TimeZone</code> represents a time zone offset, and also figures out daylight
59  * savings.
60  *
61  * <p>
62  * Typically, you get a <code>TimeZone</code> using <code>getDefault</code>
63  * which creates a <code>TimeZone</code> based on the time zone where the program
64  * is running. For example, for a program running in Japan, <code>getDefault</code>
65  * creates a <code>TimeZone</code> object based on Japanese Standard Time.
66  *
67  * <p>
68  * You can also get a <code>TimeZone</code> using <code>getTimeZone</code>
69  * along with a time zone ID. For instance, the time zone ID for the
70  * U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a
71  * U.S. Pacific Time <code>TimeZone</code> object with:
72  * <blockquote><pre>
73  * TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
74  * </pre></blockquote>
75  * You can use the <code>getAvailableIDs</code> method to iterate through
76  * all the supported time zone IDs. You can then choose a
77  * supported ID to get a <code>TimeZone</code>.
78  * If the time zone you want is not represented by one of the
79  * supported IDs, then a custom time zone ID can be specified to
80  * produce a TimeZone. The syntax of a custom time zone ID is:
81  *
82  * <blockquote><pre>
83  * <a name="CustomID"><i>CustomID:</i></a>
84  *         <code>GMT</code> <i>Sign</i> <i>Hours</i> <code>:</code> <i>Minutes</i>
85  *         <code>GMT</code> <i>Sign</i> <i>Hours</i> <i>Minutes</i>
86  *         <code>GMT</code> <i>Sign</i> <i>Hours</i>
87  * <i>Sign:</i> one of
88  *         <code>+ -</code>
89  * <i>Hours:</i>
90  *         <i>Digit</i>
91  *         <i>Digit</i> <i>Digit</i>
92  * <i>Minutes:</i>
93  *         <i>Digit</i> <i>Digit</i>
94  * <i>Digit:</i> one of
95  *         <code>0 1 2 3 4 5 6 7 8 9</code>
96  * </pre></blockquote>
97  *
98  * <i>Hours</i> must be between 0 to 23 and <i>Minutes</i> must be
99  * between 00 to 59.  For example, "GMT+10" and "GMT+0010" mean ten
100  * hours and ten minutes ahead of GMT, respectively.
101  * <p>
102  * The format is locale independent and digits must be taken from the
103  * Basic Latin block of the Unicode standard. No daylight saving time
104  * transition schedule can be specified with a custom time zone ID. If
105  * the specified string doesn't match the syntax, <code>"GMT"</code>
106  * is used.
107  * <p>
108  * When creating a <code>TimeZone</code>, the specified custom time
109  * zone ID is normalized in the following syntax:
110  * <blockquote><pre>
111  * <a name="NormalizedCustomID"><i>NormalizedCustomID:</i></a>
112  *         <code>GMT</code> <i>Sign</i> <i>TwoDigitHours</i> <code>:</code> <i>Minutes</i>
113  * <i>Sign:</i> one of
114  *         <code>+ -</code>
115  * <i>TwoDigitHours:</i>
116  *         <i>Digit</i> <i>Digit</i>
117  * <i>Minutes:</i>
118  *         <i>Digit</i> <i>Digit</i>
119  * <i>Digit:</i> one of
120  *         <code>0 1 2 3 4 5 6 7 8 9</code>
121  * </pre></blockquote>
122  * For example, TimeZone.getTimeZone("GMT-8").getID() returns "GMT-08:00".
123  *
124  * <h3>Three-letter time zone IDs</h3>
125  *
126  * For compatibility with JDK 1.1.x, some other three-letter time zone IDs
127  * (such as "PST", "CTT", "AST") are also supported. However, <strong>their
128  * use is deprecated</strong> because the same abbreviation is often used
129  * for multiple time zones (for example, "CST" could be U.S. "Central Standard
130  * Time" and "China Standard Time"), and the Java platform can then only
131  * recognize one of them.
132  *
133  *
134  * @see          Calendar
135  * @see          GregorianCalendar
136  * @see          SimpleTimeZone
137  * @author       Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
138  * @since        JDK1.1
139  */
140 abstract public class TimeZone implements Serializable, Cloneable {
141     /**
142      * Sole constructor.  (For invocation by subclass constructors, typically
143      * implicit.)
144      */
TimeZone()145     public TimeZone() {
146     }
147 
148     /**
149      * A style specifier for <code>getDisplayName()</code> indicating
150      * a short name, such as "PST."
151      * @see #LONG
152      * @since 1.2
153      */
154     public static final int SHORT = 0;
155 
156     /**
157      * A style specifier for <code>getDisplayName()</code> indicating
158      * a long name, such as "Pacific Standard Time."
159      * @see #SHORT
160      * @since 1.2
161      */
162     public static final int LONG  = 1;
163 
164     // Android-changed: Use a preload holder to allow compile-time initialization of TimeZone and
165     // dependents.
166     private static class NoImagePreloadHolder {
167         public static final Pattern CUSTOM_ZONE_ID_PATTERN = Pattern.compile("^GMT[-+](\\d{1,2})(:?(\\d\\d))?$");
168     }
169 
170     // Proclaim serialization compatibility with JDK 1.1
171     static final long serialVersionUID = 3581463369166924961L;
172 
173     // Android-changed: common timezone instances.
174     private static final TimeZone GMT = new SimpleTimeZone(0, "GMT");
175     private static final TimeZone UTC = new SimpleTimeZone(0, "UTC");
176 
177     /**
178      * Gets the time zone offset, for current date, modified in case of
179      * daylight savings. This is the offset to add to UTC to get local time.
180      * <p>
181      * This method returns a historically correct offset if an
182      * underlying <code>TimeZone</code> implementation subclass
183      * supports historical Daylight Saving Time schedule and GMT
184      * offset changes.
185      *
186      * @param era the era of the given date.
187      * @param year the year in the given date.
188      * @param month the month in the given date.
189      * Month is 0-based. e.g., 0 for January.
190      * @param day the day-in-month of the given date.
191      * @param dayOfWeek the day-of-week of the given date.
192      * @param milliseconds the milliseconds in day in <em>standard</em>
193      * local time.
194      *
195      * @return the offset in milliseconds to add to GMT to get local time.
196      *
197      * @see Calendar#ZONE_OFFSET
198      * @see Calendar#DST_OFFSET
199      */
getOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds)200     public abstract int getOffset(int era, int year, int month, int day,
201                                   int dayOfWeek, int milliseconds);
202 
203     /**
204      * Returns the offset of this time zone from UTC at the specified
205      * date. If Daylight Saving Time is in effect at the specified
206      * date, the offset value is adjusted with the amount of daylight
207      * saving.
208      * <p>
209      * This method returns a historically correct offset value if an
210      * underlying TimeZone implementation subclass supports historical
211      * Daylight Saving Time schedule and GMT offset changes.
212      *
213      * @param date the date represented in milliseconds since January 1, 1970 00:00:00 GMT
214      * @return the amount of time in milliseconds to add to UTC to get local time.
215      *
216      * @see Calendar#ZONE_OFFSET
217      * @see Calendar#DST_OFFSET
218      * @since 1.4
219      */
getOffset(long date)220     public int getOffset(long date) {
221         if (inDaylightTime(new Date(date))) {
222             return getRawOffset() + getDSTSavings();
223         }
224         return getRawOffset();
225     }
226 
227     /**
228      * Gets the raw GMT offset and the amount of daylight saving of this
229      * time zone at the given time.
230      * @param date the milliseconds (since January 1, 1970,
231      * 00:00:00.000 GMT) at which the time zone offset and daylight
232      * saving amount are found
233      * @param offsets an array of int where the raw GMT offset
234      * (offset[0]) and daylight saving amount (offset[1]) are stored,
235      * or null if those values are not needed. The method assumes that
236      * the length of the given array is two or larger.
237      * @return the total amount of the raw GMT offset and daylight
238      * saving at the specified date.
239      *
240      * @see Calendar#ZONE_OFFSET
241      * @see Calendar#DST_OFFSET
242      */
getOffsets(long date, int[] offsets)243     int getOffsets(long date, int[] offsets) {
244         int rawoffset = getRawOffset();
245         int dstoffset = 0;
246         if (inDaylightTime(new Date(date))) {
247             dstoffset = getDSTSavings();
248         }
249         if (offsets != null) {
250             offsets[0] = rawoffset;
251             offsets[1] = dstoffset;
252         }
253         return rawoffset + dstoffset;
254     }
255 
256     /**
257      * Sets the base time zone offset to GMT.
258      * This is the offset to add to UTC to get local time.
259      * <p>
260      * If an underlying <code>TimeZone</code> implementation subclass
261      * supports historical GMT offset changes, the specified GMT
262      * offset is set as the latest GMT offset and the difference from
263      * the known latest GMT offset value is used to adjust all
264      * historical GMT offset values.
265      *
266      * @param offsetMillis the given base time zone offset to GMT.
267      */
setRawOffset(int offsetMillis)268     abstract public void setRawOffset(int offsetMillis);
269 
270     /**
271      * Returns the amount of time in milliseconds to add to UTC to get
272      * standard time in this time zone. Because this value is not
273      * affected by daylight saving time, it is called <I>raw
274      * offset</I>.
275      * <p>
276      * If an underlying <code>TimeZone</code> implementation subclass
277      * supports historical GMT offset changes, the method returns the
278      * raw offset value of the current date. In Honolulu, for example,
279      * its raw offset changed from GMT-10:30 to GMT-10:00 in 1947, and
280      * this method always returns -36000000 milliseconds (i.e., -10
281      * hours).
282      *
283      * @return the amount of raw offset time in milliseconds to add to UTC.
284      * @see Calendar#ZONE_OFFSET
285      */
getRawOffset()286     public abstract int getRawOffset();
287 
288     /**
289      * Gets the ID of this time zone.
290      * @return the ID of this time zone.
291      */
getID()292     public String getID()
293     {
294         return ID;
295     }
296 
297     /**
298      * Sets the time zone ID. This does not change any other data in
299      * the time zone object.
300      * @param ID the new time zone ID.
301      */
setID(String ID)302     public void setID(String ID)
303     {
304         if (ID == null) {
305             throw new NullPointerException();
306         }
307         this.ID = ID;
308     }
309 
310     /**
311      * Returns a long standard time name of this {@code TimeZone} suitable for
312      * presentation to the user in the default locale.
313      *
314      * <p>This method is equivalent to:
315      * <blockquote><pre>
316      * getDisplayName(false, {@link #LONG},
317      *                Locale.getDefault({@link Locale.Category#DISPLAY}))
318      * </pre></blockquote>
319      *
320      * @return the human-readable name of this time zone in the default locale.
321      * @since 1.2
322      * @see #getDisplayName(boolean, int, Locale)
323      * @see Locale#getDefault(Locale.Category)
324      * @see Locale.Category
325      */
getDisplayName()326     public final String getDisplayName() {
327         return getDisplayName(false, LONG,
328                               Locale.getDefault(Locale.Category.DISPLAY));
329     }
330 
331     /**
332      * Returns a long standard time name of this {@code TimeZone} suitable for
333      * presentation to the user in the specified {@code locale}.
334      *
335      * <p>This method is equivalent to:
336      * <blockquote><pre>
337      * getDisplayName(false, {@link #LONG}, locale)
338      * </pre></blockquote>
339      *
340      * @param locale the locale in which to supply the display name.
341      * @return the human-readable name of this time zone in the given locale.
342      * @exception NullPointerException if {@code locale} is {@code null}.
343      * @since 1.2
344      * @see #getDisplayName(boolean, int, Locale)
345      */
getDisplayName(Locale locale)346     public final String getDisplayName(Locale locale) {
347         return getDisplayName(false, LONG, locale);
348     }
349 
350     /**
351      * Returns a name in the specified {@code style} of this {@code TimeZone}
352      * suitable for presentation to the user in the default locale. If the
353      * specified {@code daylight} is {@code true}, a Daylight Saving Time name
354      * is returned (even if this {@code TimeZone} doesn't observe Daylight Saving
355      * Time). Otherwise, a Standard Time name is returned.
356      *
357      * <p>This method is equivalent to:
358      * <blockquote><pre>
359      * getDisplayName(daylight, style,
360      *                Locale.getDefault({@link Locale.Category#DISPLAY}))
361      * </pre></blockquote>
362      *
363      * @param daylight {@code true} specifying a Daylight Saving Time name, or
364      *                 {@code false} specifying a Standard Time name
365      * @param style either {@link #LONG} or {@link #SHORT}
366      * @return the human-readable name of this time zone in the default locale.
367      * @exception IllegalArgumentException if {@code style} is invalid.
368      * @since 1.2
369      * @see #getDisplayName(boolean, int, Locale)
370      * @see Locale#getDefault(Locale.Category)
371      * @see Locale.Category
372      * @see java.text.DateFormatSymbols#getZoneStrings()
373      */
getDisplayName(boolean daylight, int style)374     public final String getDisplayName(boolean daylight, int style) {
375         return getDisplayName(daylight, style,
376                               Locale.getDefault(Locale.Category.DISPLAY));
377     }
378 
379     /**
380      * Returns the {@link #SHORT short} or {@link #LONG long} name of this time
381      * zone with either standard or daylight time, as written in {@code locale}.
382      * If the name is not available, the result is in the format
383      * {@code GMT[+-]hh:mm}.
384      *
385      * @param daylightTime true for daylight time, false for standard time.
386      * @param style either {@link TimeZone#LONG} or {@link TimeZone#SHORT}.
387      * @param locale the display locale.
388      */
getDisplayName(boolean daylightTime, int style, Locale locale)389     public String getDisplayName(boolean daylightTime, int style, Locale locale) {
390         if (style != SHORT && style != LONG) {
391             throw new IllegalArgumentException("Illegal style: " + style);
392         }
393 
394         // Android-changed: implement using libcore.icu.TimeZoneNames
395         String[][] zoneStrings = TimeZoneNames.getZoneStrings(locale);
396         String result = TimeZoneNames.getDisplayName(zoneStrings, getID(), daylightTime, style);
397         if (result != null) {
398             return result;
399         }
400 
401         // If we get here, it's because icu4c has nothing for us. Most commonly, this is in the
402         // case of short names. For Pacific/Fiji, for example, icu4c has nothing better to offer
403         // than "GMT+12:00". Why do we re-do this work ourselves? Because we have up-to-date
404         // time zone transition data, which icu4c _doesn't_ use --- it uses its own baked-in copy,
405         // which only gets updated when we update icu4c. http://b/7955614 and http://b/8026776.
406 
407         // TODO: should we generate these once, in TimeZoneNames.getDisplayName? Revisit when we
408         // upgrade to icu4c 50 and rewrite the underlying native code. See also the
409         // "element[j] != null" check in SimpleDateFormat.parseTimeZone, and the extra work in
410         // DateFormatSymbols.getZoneStrings.
411         int offsetMillis = getRawOffset();
412         if (daylightTime) {
413             offsetMillis += getDSTSavings();
414         }
415         return createGmtOffsetString(true /* includeGmt */, true /* includeMinuteSeparator */,
416                 offsetMillis);
417     }
418 
419     /**
420      * Returns a string representation of an offset from UTC.
421      *
422      * <p>The format is "[GMT](+|-)HH[:]MM". The output is not localized.
423      *
424      * @param includeGmt true to include "GMT", false to exclude
425      * @param includeMinuteSeparator true to include the separator between hours and minutes, false
426      *     to exclude.
427      * @param offsetMillis the offset from UTC
428      *
429      * @hide used internally by SimpleDateFormat
430      */
createGmtOffsetString(boolean includeGmt, boolean includeMinuteSeparator, int offsetMillis)431     public static String createGmtOffsetString(boolean includeGmt,
432             boolean includeMinuteSeparator, int offsetMillis) {
433         int offsetMinutes = offsetMillis / 60000;
434         char sign = '+';
435         if (offsetMinutes < 0) {
436             sign = '-';
437             offsetMinutes = -offsetMinutes;
438         }
439         StringBuilder builder = new StringBuilder(9);
440         if (includeGmt) {
441             builder.append("GMT");
442         }
443         builder.append(sign);
444         appendNumber(builder, 2, offsetMinutes / 60);
445         if (includeMinuteSeparator) {
446             builder.append(':');
447         }
448         appendNumber(builder, 2, offsetMinutes % 60);
449         return builder.toString();
450     }
451 
appendNumber(StringBuilder builder, int count, int value)452     private static void appendNumber(StringBuilder builder, int count, int value) {
453         String string = Integer.toString(value);
454         for (int i = 0; i < count - string.length(); i++) {
455             builder.append('0');
456         }
457         builder.append(string);
458     }
459 
460     /**
461      * Returns the amount of time to be added to local standard time
462      * to get local wall clock time.
463      *
464      * <p>The default implementation returns 3600000 milliseconds
465      * (i.e., one hour) if a call to {@link #useDaylightTime()}
466      * returns {@code true}. Otherwise, 0 (zero) is returned.
467      *
468      * <p>If an underlying {@code TimeZone} implementation subclass
469      * supports historical and future Daylight Saving Time schedule
470      * changes, this method returns the amount of saving time of the
471      * last known Daylight Saving Time rule that can be a future
472      * prediction.
473      *
474      * <p>If the amount of saving time at any given time stamp is
475      * required, construct a {@link Calendar} with this {@code
476      * TimeZone} and the time stamp, and call {@link Calendar#get(int)
477      * Calendar.get}{@code (}{@link Calendar#DST_OFFSET}{@code )}.
478      *
479      * @return the amount of saving time in milliseconds
480      * @since 1.4
481      * @see #inDaylightTime(Date)
482      * @see #getOffset(long)
483      * @see #getOffset(int,int,int,int,int,int)
484      * @see Calendar#ZONE_OFFSET
485      */
getDSTSavings()486     public int getDSTSavings() {
487         if (useDaylightTime()) {
488             return 3600000;
489         }
490         return 0;
491     }
492 
493     /**
494      * Queries if this {@code TimeZone} uses Daylight Saving Time.
495      *
496      * <p>If an underlying {@code TimeZone} implementation subclass
497      * supports historical and future Daylight Saving Time schedule
498      * changes, this method refers to the last known Daylight Saving Time
499      * rule that can be a future prediction and may not be the same as
500      * the current rule. Consider calling {@link #observesDaylightTime()}
501      * if the current rule should also be taken into account.
502      *
503      * @return {@code true} if this {@code TimeZone} uses Daylight Saving Time,
504      *         {@code false}, otherwise.
505      * @see #inDaylightTime(Date)
506      * @see Calendar#DST_OFFSET
507      */
useDaylightTime()508     public abstract boolean useDaylightTime();
509 
510     /**
511      * Returns {@code true} if this {@code TimeZone} is currently in
512      * Daylight Saving Time, or if a transition from Standard Time to
513      * Daylight Saving Time occurs at any future time.
514      *
515      * <p>The default implementation returns {@code true} if
516      * {@code useDaylightTime()} or {@code inDaylightTime(new Date())}
517      * returns {@code true}.
518      *
519      * @return {@code true} if this {@code TimeZone} is currently in
520      * Daylight Saving Time, or if a transition from Standard Time to
521      * Daylight Saving Time occurs at any future time; {@code false}
522      * otherwise.
523      * @since 1.7
524      * @see #useDaylightTime()
525      * @see #inDaylightTime(Date)
526      * @see Calendar#DST_OFFSET
527      */
observesDaylightTime()528     public boolean observesDaylightTime() {
529         return useDaylightTime() || inDaylightTime(new Date());
530     }
531 
532     /**
533      * Queries if the given {@code date} is in Daylight Saving Time in
534      * this time zone.
535      *
536      * @param date the given Date.
537      * @return {@code true} if the given date is in Daylight Saving Time,
538      *         {@code false}, otherwise.
539      */
inDaylightTime(Date date)540     abstract public boolean inDaylightTime(Date date);
541 
542     /**
543      * Gets the <code>TimeZone</code> for the given ID.
544      *
545      * @param id the ID for a <code>TimeZone</code>, either an abbreviation
546      * such as "PST", a full name such as "America/Los_Angeles", or a custom
547      * ID such as "GMT-8:00". Note that the support of abbreviations is
548      * for JDK 1.1.x compatibility only and full names should be used.
549      *
550      * @return the specified <code>TimeZone</code>, or the GMT zone if the given ID
551      * cannot be understood.
552      */
553     // Android-changed: param s/ID/id; use ZoneInfoDB instead of ZoneInfo class.
getTimeZone(String id)554     public static synchronized TimeZone getTimeZone(String id) {
555         if (id == null) {
556             throw new NullPointerException("id == null");
557         }
558 
559         // Special cases? These can clone an existing instance.
560         if (id.length() == 3) {
561             if (id.equals("GMT")) {
562                 return (TimeZone) GMT.clone();
563             }
564             if (id.equals("UTC")) {
565                 return (TimeZone) UTC.clone();
566             }
567         }
568 
569         // In the database?
570         TimeZone zone = null;
571         try {
572             zone = ZoneInfoDB.getInstance().makeTimeZone(id);
573         } catch (IOException ignored) {
574         }
575 
576         // Custom time zone?
577         if (zone == null && id.length() > 3 && id.startsWith("GMT")) {
578             zone = getCustomTimeZone(id);
579         }
580 
581         // We never return null; on failure we return the equivalent of "GMT".
582         return (zone != null) ? zone : (TimeZone) GMT.clone();
583     }
584 
585     /**
586      * Gets the {@code TimeZone} for the given {@code zoneId}.
587      *
588      * @param zoneId a {@link ZoneId} from which the time zone ID is obtained
589      * @return the specified {@code TimeZone}, or the GMT zone if the given ID
590      *         cannot be understood.
591      * @throws NullPointerException if {@code zoneId} is {@code null}
592      * @since 1.8
593      */
getTimeZone(ZoneId zoneId)594     public static TimeZone getTimeZone(ZoneId zoneId) {
595         String tzid = zoneId.getId(); // throws an NPE if null
596         char c = tzid.charAt(0);
597         if (c == '+' || c == '-') {
598             tzid = "GMT" + tzid;
599         } else if (c == 'Z' && tzid.length() == 1) {
600             tzid = "UTC";
601         }
602         return getTimeZone(tzid);
603     }
604 
605     /**
606      * Converts this {@code TimeZone} object to a {@code ZoneId}.
607      *
608      * @return a {@code ZoneId} representing the same time zone as this
609      *         {@code TimeZone}
610      * @since 1.8
611      */
toZoneId()612     public ZoneId toZoneId() {
613         // Android-changed: don't support "old mapping"
614         return ZoneId.of(getID(), ZoneId.SHORT_IDS);
615     }
616 
617     /**
618      * Returns a new SimpleTimeZone for an ID of the form "GMT[+|-]hh[[:]mm]", or null.
619      */
getCustomTimeZone(String id)620     private static TimeZone getCustomTimeZone(String id) {
621         Matcher m = NoImagePreloadHolder.CUSTOM_ZONE_ID_PATTERN.matcher(id);
622         if (!m.matches()) {
623             return null;
624         }
625 
626         int hour;
627         int minute = 0;
628         try {
629             hour = Integer.parseInt(m.group(1));
630             if (m.group(3) != null) {
631                 minute = Integer.parseInt(m.group(3));
632             }
633         } catch (NumberFormatException impossible) {
634             throw new AssertionError(impossible);
635         }
636 
637         if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
638             return null;
639         }
640 
641         char sign = id.charAt(3);
642         int raw = (hour * 3600000) + (minute * 60000);
643         if (sign == '-') {
644             raw = -raw;
645         }
646 
647         String cleanId = String.format(Locale.ROOT, "GMT%c%02d:%02d", sign, hour, minute);
648 
649         return new SimpleTimeZone(raw, cleanId);
650     }
651 
652     /**
653      * Gets the available IDs according to the given time zone offset in milliseconds.
654      *
655      * @param rawOffset the given time zone GMT offset in milliseconds.
656      * @return an array of IDs, where the time zone for that ID has
657      * the specified GMT offset. For example, "America/Phoenix" and "America/Denver"
658      * both have GMT-07:00, but differ in daylight saving behavior.
659      * @see #getRawOffset()
660      */
getAvailableIDs(int rawOffset)661     public static synchronized String[] getAvailableIDs(int rawOffset) {
662         return ZoneInfoDB.getInstance().getAvailableIDs(rawOffset);
663     }
664 
665     /**
666      * Gets all the available IDs supported.
667      * @return an array of IDs.
668      */
getAvailableIDs()669     public static synchronized String[] getAvailableIDs() {
670         return ZoneInfoDB.getInstance().getAvailableIDs();
671     }
672 
673     /**
674      * Gets the platform defined TimeZone ID.
675      **/
getSystemTimeZoneID(String javaHome, String country)676     private static native String getSystemTimeZoneID(String javaHome,
677                                                      String country);
678 
679     /**
680      * Gets the custom time zone ID based on the GMT offset of the
681      * platform. (e.g., "GMT+08:00")
682      */
getSystemGMTOffsetID()683     private static native String getSystemGMTOffsetID();
684 
685     /**
686      * Gets the default <code>TimeZone</code> for this host.
687      * The source of the default <code>TimeZone</code>
688      * may vary with implementation.
689      * @return a default <code>TimeZone</code>.
690      * @see #setDefault
691      */
getDefault()692     public static TimeZone getDefault() {
693         return (TimeZone) getDefaultRef().clone();
694     }
695 
696     /**
697      * Returns the reference to the default TimeZone object. This
698      * method doesn't create a clone.
699      */
getDefaultRef()700     static synchronized TimeZone getDefaultRef() {
701         if (defaultTimeZone == null) {
702             TimezoneGetter tzGetter = TimezoneGetter.getInstance();
703             String zoneName = (tzGetter != null) ? tzGetter.getId() : null;
704             if (zoneName != null) {
705                 zoneName = zoneName.trim();
706             }
707             if (zoneName == null || zoneName.isEmpty()) {
708                 try {
709                     // On the host, we can find the configured timezone here.
710                     zoneName = IoUtils.readFileAsString("/etc/timezone");
711                 } catch (IOException ex) {
712                     // "vogar --mode device" can end up here.
713                     // TODO: give libcore access to Android system properties and read "persist.sys.timezone".
714                     zoneName = "GMT";
715                 }
716             }
717             defaultTimeZone = TimeZone.getTimeZone(zoneName);
718         }
719         return defaultTimeZone;
720     }
721 
722     /**
723      * Sets the {@code TimeZone} that is returned by the {@code getDefault}
724      * method. {@code timeZone} is cached. If {@code timeZone} is null, the cached
725      * default {@code TimeZone} is cleared. This method doesn't change the value
726      * of the {@code user.timezone} property.
727      *
728      * @param timeZone the new default {@code TimeZone}, or null
729      * @see #getDefault
730      */
731     // Android-changed: s/zone/timeZone, synchronized, removed mention of SecurityException
setDefault(TimeZone timeZone)732     public synchronized static void setDefault(TimeZone timeZone)
733     {
734         SecurityManager sm = System.getSecurityManager();
735         if (sm != null) {
736             sm.checkPermission(new PropertyPermission
737                     ("user.timezone", "write"));
738         }
739         defaultTimeZone = timeZone != null ? (TimeZone) timeZone.clone() : null;
740         // Android-changed: notify ICU4J of changed default TimeZone.
741         android.icu.util.TimeZone.clearCachedDefault();
742     }
743 
744     /**
745      * Returns true if this zone has the same rule and offset as another zone.
746      * That is, if this zone differs only in ID, if at all.  Returns false
747      * if the other zone is null.
748      * @param other the <code>TimeZone</code> object to be compared with
749      * @return true if the other zone is not null and is the same as this one,
750      * with the possible exception of the ID
751      * @since 1.2
752      */
hasSameRules(TimeZone other)753     public boolean hasSameRules(TimeZone other) {
754         return other != null && getRawOffset() == other.getRawOffset() &&
755             useDaylightTime() == other.useDaylightTime();
756     }
757 
758     /**
759      * Creates a copy of this <code>TimeZone</code>.
760      *
761      * @return a clone of this <code>TimeZone</code>
762      */
clone()763     public Object clone()
764     {
765         try {
766             TimeZone other = (TimeZone) super.clone();
767             other.ID = ID;
768             return other;
769         } catch (CloneNotSupportedException e) {
770             throw new InternalError(e);
771         }
772     }
773 
774     /**
775      * The null constant as a TimeZone.
776      */
777     static final TimeZone NO_TIMEZONE = null;
778 
779     // =======================privates===============================
780 
781     /**
782      * The string identifier of this <code>TimeZone</code>.  This is a
783      * programmatic identifier used internally to look up <code>TimeZone</code>
784      * objects from the system table and also to map them to their localized
785      * display names.  <code>ID</code> values are unique in the system
786      * table but may not be for dynamically created zones.
787      * @serial
788      */
789     private String           ID;
790     private static volatile TimeZone defaultTimeZone;
791 }
792