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