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