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