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