1 /*
   2  * Copyright (c) 1996, 2017, 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.ObjectInputStream;
  42 import java.io.ObjectOutputStream;
  43 import java.io.IOException;
  44 import java.io.InvalidObjectException;
  45 import sun.util.calendar.CalendarSystem;
  46 import sun.util.calendar.CalendarUtils;
  47 import sun.util.calendar.BaseCalendar;
  48 import sun.util.calendar.Gregorian;
  49 
  50 /**
  51  * <code>SimpleTimeZone</code> is a concrete subclass of <code>TimeZone</code>
  52  * that represents a time zone for use with a Gregorian calendar.
  53  * The class holds an offset from GMT, called <em>raw offset</em>, and start
  54  * and end rules for a daylight saving time schedule.  Since it only holds
  55  * single values for each, it cannot handle historical changes in the offset
  56  * from GMT and the daylight saving schedule, except that the {@link
  57  * #setStartYear setStartYear} method can specify the year when the daylight
  58  * saving time schedule starts in effect.
  59  * <p>
  60  * To construct a <code>SimpleTimeZone</code> with a daylight saving time
  61  * schedule, the schedule can be described with a set of rules,
  62  * <em>start-rule</em> and <em>end-rule</em>. A day when daylight saving time
  63  * starts or ends is specified by a combination of <em>month</em>,
  64  * <em>day-of-month</em>, and <em>day-of-week</em> values. The <em>month</em>
  65  * value is represented by a Calendar {@link Calendar#MONTH MONTH} field
  66  * value, such as {@link Calendar#MARCH}. The <em>day-of-week</em> value is
  67  * represented by a Calendar {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} value,
  68  * such as {@link Calendar#SUNDAY SUNDAY}. The meanings of value combinations
  69  * are as follows.
  70  *
  71  * <ul>
  72  * <li><b>Exact day of month</b><br>
  73  * To specify an exact day of month, set the <em>month</em> and
  74  * <em>day-of-month</em> to an exact value, and <em>day-of-week</em> to zero. For
  75  * example, to specify March 1, set the <em>month</em> to {@link Calendar#MARCH
  76  * MARCH}, <em>day-of-month</em> to 1, and <em>day-of-week</em> to 0.</li>
  77  *
  78  * <li><b>Day of week on or after day of month</b><br>
  79  * To specify a day of week on or after an exact day of month, set the
  80  * <em>month</em> to an exact month value, <em>day-of-month</em> to the day on
  81  * or after which the rule is applied, and <em>day-of-week</em> to a negative {@link
  82  * Calendar#DAY_OF_WEEK DAY_OF_WEEK} field value. For example, to specify the
  83  * second Sunday of April, set <em>month</em> to {@link Calendar#APRIL APRIL},
  84  * <em>day-of-month</em> to 8, and <em>day-of-week</em> to <code>-</code>{@link
  85  * Calendar#SUNDAY SUNDAY}.</li>
  86  *
  87  * <li><b>Day of week on or before day of month</b><br>
  88  * To specify a day of the week on or before an exact day of the month, set
  89  * <em>day-of-month</em> and <em>day-of-week</em> to a negative value. For
  90  * example, to specify the last Wednesday on or before the 21st of March, set
  91  * <em>month</em> to {@link Calendar#MARCH MARCH}, <em>day-of-month</em> is -21
  92  * and <em>day-of-week</em> is <code>-</code>{@link Calendar#WEDNESDAY WEDNESDAY}. </li>
  93  *
  94  * <li><b>Last day-of-week of month</b><br>
  95  * To specify, the last day-of-week of the month, set <em>day-of-week</em> to a
  96  * {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} value and <em>day-of-month</em> to
  97  * -1. For example, to specify the last Sunday of October, set <em>month</em>
  98  * to {@link Calendar#OCTOBER OCTOBER}, <em>day-of-week</em> to {@link
  99  * Calendar#SUNDAY SUNDAY} and <em>day-of-month</em> to -1.  </li>
 100  *
 101  * </ul>
 102  * The time of the day at which daylight saving time starts or ends is
 103  * specified by a millisecond value within the day. There are three kinds of
 104  * <em>mode</em>s to specify the time: {@link #WALL_TIME}, {@link
 105  * #STANDARD_TIME} and {@link #UTC_TIME}. For example, if daylight
 106  * saving time ends
 107  * at 2:00 am in the wall clock time, it can be specified by 7200000
 108  * milliseconds in the {@link #WALL_TIME} mode. In this case, the wall clock time
 109  * for an <em>end-rule</em> means the same thing as the daylight time.
 110  * <p>
 111  * The following are examples of parameters for constructing time zone objects.
 112  * <pre><code>
 113  *      // Base GMT offset: -8:00
 114  *      // DST starts:      at 2:00am in standard time
 115  *      //                  on the first Sunday in April
 116  *      // DST ends:        at 2:00am in daylight time
 117  *      //                  on the last Sunday in October
 118  *      // Save:            1 hour
 119  *      SimpleTimeZone(-28800000,
 120  *                     "America/Los_Angeles",
 121  *                     Calendar.APRIL, 1, -Calendar.SUNDAY,
 122  *                     7200000,
 123  *                     Calendar.OCTOBER, -1, Calendar.SUNDAY,
 124  *                     7200000,
 125  *                     3600000)
 126  *
 127  *      // Base GMT offset: +1:00
 128  *      // DST starts:      at 1:00am in UTC time
 129  *      //                  on the last Sunday in March
 130  *      // DST ends:        at 1:00am in UTC time
 131  *      //                  on the last Sunday in October
 132  *      // Save:            1 hour
 133  *      SimpleTimeZone(3600000,
 134  *                     "Europe/Paris",
 135  *                     Calendar.MARCH, -1, Calendar.SUNDAY,
 136  *                     3600000, SimpleTimeZone.UTC_TIME,
 137  *                     Calendar.OCTOBER, -1, Calendar.SUNDAY,
 138  *                     3600000, SimpleTimeZone.UTC_TIME,
 139  *                     3600000)
 140  * </code></pre>
 141  * These parameter rules are also applicable to the set rule methods, such as
 142  * <code>setStartRule</code>.
 143  *
 144  * @since 1.1
 145  * @see      Calendar
 146  * @see      GregorianCalendar
 147  * @see      TimeZone
 148  * @author   David Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu
 149  */
 150 
 151 public class SimpleTimeZone extends TimeZone {
 152     /**
 153      * Constructs a SimpleTimeZone with the given base time zone offset from GMT
 154      * and time zone ID with no daylight saving time schedule.
 155      *
 156      * @param rawOffset  The base time zone offset in milliseconds to GMT.
 157      * @param ID         The time zone name that is given to this instance.
 158      */
 159     public SimpleTimeZone(int rawOffset, String ID)
 160     {
 161         this.rawOffset = rawOffset;
 162         setID (ID);
 163         dstSavings = millisPerHour; // In case user sets rules later
 164     }
 165 
 166     /**
 167      * Constructs a SimpleTimeZone with the given base time zone offset from
 168      * GMT, time zone ID, and rules for starting and ending the daylight
 169      * time.
 170      * Both <code>startTime</code> and <code>endTime</code> are specified to be
 171      * represented in the wall clock time. The amount of daylight saving is
 172      * assumed to be 3600000 milliseconds (i.e., one hour). This constructor is
 173      * equivalent to:
 174      * <pre><code>
 175      *     SimpleTimeZone(rawOffset,
 176      *                    ID,
 177      *                    startMonth,
 178      *                    startDay,
 179      *                    startDayOfWeek,
 180      *                    startTime,
 181      *                    SimpleTimeZone.{@link #WALL_TIME},
 182      *                    endMonth,
 183      *                    endDay,
 184      *                    endDayOfWeek,
 185      *                    endTime,
 186      *                    SimpleTimeZone.{@link #WALL_TIME},
 187      *                    3600000)
 188      * </code></pre>
 189      *
 190      * @param rawOffset       The given base time zone offset from GMT.
 191      * @param ID              The time zone ID which is given to this object.
 192      * @param startMonth      The daylight saving time starting month. Month is
 193      *                        a {@link Calendar#MONTH MONTH} field value (0-based. e.g., 0
 194      *                        for January).
 195      * @param startDay        The day of the month on which the daylight saving time starts.
 196      *                        See the class description for the special cases of this parameter.
 197      * @param startDayOfWeek  The daylight saving time starting day-of-week.
 198      *                        See the class description for the special cases of this parameter.
 199      * @param startTime       The daylight saving time starting time in local wall clock
 200      *                        time (in milliseconds within the day), which is local
 201      *                        standard time in this case.
 202      * @param endMonth        The daylight saving time ending month. Month is
 203      *                        a {@link Calendar#MONTH MONTH} field
 204      *                        value (0-based. e.g., 9 for October).
 205      * @param endDay          The day of the month on which the daylight saving time ends.
 206      *                        See the class description for the special cases of this parameter.
 207      * @param endDayOfWeek    The daylight saving time ending day-of-week.
 208      *                        See the class description for the special cases of this parameter.
 209      * @param endTime         The daylight saving ending time in local wall clock time,
 210      *                        (in milliseconds within the day) which is local daylight
 211      *                        time in this case.
 212      * @exception IllegalArgumentException if the month, day, dayOfWeek, or time
 213      * parameters are out of range for the start or end rule
 214      */
 215     public SimpleTimeZone(int rawOffset, String ID,
 216                           int startMonth, int startDay, int startDayOfWeek, int startTime,
 217                           int endMonth, int endDay, int endDayOfWeek, int endTime)
 218     {
 219         this(rawOffset, ID,
 220              startMonth, startDay, startDayOfWeek, startTime, WALL_TIME,
 221              endMonth, endDay, endDayOfWeek, endTime, WALL_TIME,
 222              millisPerHour);
 223     }
 224 
 225     /**
 226      * Constructs a SimpleTimeZone with the given base time zone offset from
 227      * GMT, time zone ID, and rules for starting and ending the daylight
 228      * time.
 229      * Both <code>startTime</code> and <code>endTime</code> are assumed to be
 230      * represented in the wall clock time. This constructor is equivalent to:
 231      * <pre><code>
 232      *     SimpleTimeZone(rawOffset,
 233      *                    ID,
 234      *                    startMonth,
 235      *                    startDay,
 236      *                    startDayOfWeek,
 237      *                    startTime,
 238      *                    SimpleTimeZone.{@link #WALL_TIME},
 239      *                    endMonth,
 240      *                    endDay,
 241      *                    endDayOfWeek,
 242      *                    endTime,
 243      *                    SimpleTimeZone.{@link #WALL_TIME},
 244      *                    dstSavings)
 245      * </code></pre>
 246      *
 247      * @param rawOffset       The given base time zone offset from GMT.
 248      * @param ID              The time zone ID which is given to this object.
 249      * @param startMonth      The daylight saving time starting month. Month is
 250      *                        a {@link Calendar#MONTH MONTH} field
 251      *                        value (0-based. e.g., 0 for January).
 252      * @param startDay        The day of the month on which the daylight saving time starts.
 253      *                        See the class description for the special cases of this parameter.
 254      * @param startDayOfWeek  The daylight saving time starting day-of-week.
 255      *                        See the class description for the special cases of this parameter.
 256      * @param startTime       The daylight saving time starting time in local wall clock
 257      *                        time, which is local standard time in this case.
 258      * @param endMonth        The daylight saving time ending month. Month is
 259      *                        a {@link Calendar#MONTH MONTH} field
 260      *                        value (0-based. e.g., 9 for October).
 261      * @param endDay          The day of the month on which the daylight saving time ends.
 262      *                        See the class description for the special cases of this parameter.
 263      * @param endDayOfWeek    The daylight saving time ending day-of-week.
 264      *                        See the class description for the special cases of this parameter.
 265      * @param endTime         The daylight saving ending time in local wall clock time,
 266      *                        which is local daylight time in this case.
 267      * @param dstSavings      The amount of time in milliseconds saved during
 268      *                        daylight saving time.
 269      * @exception IllegalArgumentException if the month, day, dayOfWeek, or time
 270      * parameters are out of range for the start or end rule
 271      * @since 1.2
 272      */
 273     public SimpleTimeZone(int rawOffset, String ID,
 274                           int startMonth, int startDay, int startDayOfWeek, int startTime,
 275                           int endMonth, int endDay, int endDayOfWeek, int endTime,
 276                           int dstSavings)
 277     {
 278         this(rawOffset, ID,
 279              startMonth, startDay, startDayOfWeek, startTime, WALL_TIME,
 280              endMonth, endDay, endDayOfWeek, endTime, WALL_TIME,
 281              dstSavings);
 282     }
 283 
 284     /**
 285      * Constructs a SimpleTimeZone with the given base time zone offset from
 286      * GMT, time zone ID, and rules for starting and ending the daylight
 287      * time.
 288      * This constructor takes the full set of the start and end rules
 289      * parameters, including modes of <code>startTime</code> and
 290      * <code>endTime</code>. The mode specifies either {@link #WALL_TIME wall
 291      * time} or {@link #STANDARD_TIME standard time} or {@link #UTC_TIME UTC
 292      * time}.
 293      *
 294      * @param rawOffset       The given base time zone offset from GMT.
 295      * @param ID              The time zone ID which is given to this object.
 296      * @param startMonth      The daylight saving time starting month. Month is
 297      *                        a {@link Calendar#MONTH MONTH} field
 298      *                        value (0-based. e.g., 0 for January).
 299      * @param startDay        The day of the month on which the daylight saving time starts.
 300      *                        See the class description for the special cases of this parameter.
 301      * @param startDayOfWeek  The daylight saving time starting day-of-week.
 302      *                        See the class description for the special cases of this parameter.
 303      * @param startTime       The daylight saving time starting time in the time mode
 304      *                        specified by <code>startTimeMode</code>.
 305      * @param startTimeMode   The mode of the start time specified by startTime.
 306      * @param endMonth        The daylight saving time ending month. Month is
 307      *                        a {@link Calendar#MONTH MONTH} field
 308      *                        value (0-based. e.g., 9 for October).
 309      * @param endDay          The day of the month on which the daylight saving time ends.
 310      *                        See the class description for the special cases of this parameter.
 311      * @param endDayOfWeek    The daylight saving time ending day-of-week.
 312      *                        See the class description for the special cases of this parameter.
 313      * @param endTime         The daylight saving ending time in time time mode
 314      *                        specified by <code>endTimeMode</code>.
 315      * @param endTimeMode     The mode of the end time specified by endTime
 316      * @param dstSavings      The amount of time in milliseconds saved during
 317      *                        daylight saving time.
 318      *
 319      * @exception IllegalArgumentException if the month, day, dayOfWeek, time more, or
 320      * time parameters are out of range for the start or end rule, or if a time mode
 321      * value is invalid.
 322      *
 323      * @see #WALL_TIME
 324      * @see #STANDARD_TIME
 325      * @see #UTC_TIME
 326      *
 327      * @since 1.4
 328      */
 329     public SimpleTimeZone(int rawOffset, String ID,
 330                           int startMonth, int startDay, int startDayOfWeek,
 331                           int startTime, int startTimeMode,
 332                           int endMonth, int endDay, int endDayOfWeek,
 333                           int endTime, int endTimeMode,
 334                           int dstSavings) {
 335 
 336         setID(ID);
 337         this.rawOffset      = rawOffset;
 338         this.startMonth     = startMonth;
 339         this.startDay       = startDay;
 340         this.startDayOfWeek = startDayOfWeek;
 341         this.startTime      = startTime;
 342         this.startTimeMode  = startTimeMode;
 343         this.endMonth       = endMonth;
 344         this.endDay         = endDay;
 345         this.endDayOfWeek   = endDayOfWeek;
 346         this.endTime        = endTime;
 347         this.endTimeMode    = endTimeMode;
 348         this.dstSavings     = dstSavings;
 349 
 350         // this.useDaylight is set by decodeRules
 351         decodeRules();
 352         if (dstSavings <= 0) {
 353             throw new IllegalArgumentException("Illegal daylight saving value: " + dstSavings);
 354         }
 355     }
 356 
 357     /**
 358      * Sets the daylight saving time starting year.
 359      *
 360      * @param year  The daylight saving starting year.
 361      */
 362     public void setStartYear(int year)
 363     {
 364         startYear = year;
 365         invalidateCache();
 366     }
 367 
 368     /**
 369      * Sets the daylight saving time start rule. For example, if daylight saving
 370      * time starts on the first Sunday in April at 2 am in local wall clock
 371      * time, you can set the start rule by calling:
 372      * <pre><code>setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2*60*60*1000);</code></pre>
 373      *
 374      * @param startMonth      The daylight saving time starting month. Month is
 375      *                        a {@link Calendar#MONTH MONTH} field
 376      *                        value (0-based. e.g., 0 for January).
 377      * @param startDay        The day of the month on which the daylight saving time starts.
 378      *                        See the class description for the special cases of this parameter.
 379      * @param startDayOfWeek  The daylight saving time starting day-of-week.
 380      *                        See the class description for the special cases of this parameter.
 381      * @param startTime       The daylight saving time starting time in local wall clock
 382      *                        time, which is local standard time in this case.
 383      * @exception IllegalArgumentException if the <code>startMonth</code>, <code>startDay</code>,
 384      * <code>startDayOfWeek</code>, or <code>startTime</code> parameters are out of range
 385      */
 386     public void setStartRule(int startMonth, int startDay, int startDayOfWeek, int startTime)
 387     {
 388         this.startMonth = startMonth;
 389         this.startDay = startDay;
 390         this.startDayOfWeek = startDayOfWeek;
 391         this.startTime = startTime;
 392         startTimeMode = WALL_TIME;
 393         decodeStartRule();
 394         invalidateCache();
 395     }
 396 
 397     /**
 398      * Sets the daylight saving time start rule to a fixed date within a month.
 399      * This method is equivalent to:
 400      * <pre><code>setStartRule(startMonth, startDay, 0, startTime)</code></pre>
 401      *
 402      * @param startMonth      The daylight saving time starting month. Month is
 403      *                        a {@link Calendar#MONTH MONTH} field
 404      *                        value (0-based. e.g., 0 for January).
 405      * @param startDay        The day of the month on which the daylight saving time starts.
 406      * @param startTime       The daylight saving time starting time in local wall clock
 407      *                        time, which is local standard time in this case.
 408      *                        See the class description for the special cases of this parameter.
 409      * @exception IllegalArgumentException if the <code>startMonth</code>,
 410      * <code>startDayOfMonth</code>, or <code>startTime</code> parameters are out of range
 411      * @since 1.2
 412      */
 413     public void setStartRule(int startMonth, int startDay, int startTime) {
 414         setStartRule(startMonth, startDay, 0, startTime);
 415     }
 416 
 417     /**
 418      * Sets the daylight saving time start rule to a weekday before or after the given date within
 419      * a month, e.g., the first Monday on or after the 8th.
 420      *
 421      * @param startMonth      The daylight saving time starting month. Month is
 422      *                        a {@link Calendar#MONTH MONTH} field
 423      *                        value (0-based. e.g., 0 for January).
 424      * @param startDay        The day of the month on which the daylight saving time starts.
 425      * @param startDayOfWeek  The daylight saving time starting day-of-week.
 426      * @param startTime       The daylight saving time starting time in local wall clock
 427      *                        time, which is local standard time in this case.
 428      * @param after           If true, this rule selects the first <code>dayOfWeek</code> on or
 429      *                        <em>after</em> <code>dayOfMonth</code>.  If false, this rule
 430      *                        selects the last <code>dayOfWeek</code> on or <em>before</em>
 431      *                        <code>dayOfMonth</code>.
 432      * @exception IllegalArgumentException if the <code>startMonth</code>, <code>startDay</code>,
 433      * <code>startDayOfWeek</code>, or <code>startTime</code> parameters are out of range
 434      * @since 1.2
 435      */
 436     public void setStartRule(int startMonth, int startDay, int startDayOfWeek,
 437                              int startTime, boolean after)
 438     {
 439         // TODO: this method doesn't check the initial values of dayOfMonth or dayOfWeek.
 440         if (after) {
 441             setStartRule(startMonth, startDay, -startDayOfWeek, startTime);
 442         } else {
 443             setStartRule(startMonth, -startDay, -startDayOfWeek, startTime);
 444         }
 445     }
 446 
 447     /**
 448      * Sets the daylight saving time end rule. For example, if daylight saving time
 449      * ends on the last Sunday in October at 2 am in wall clock time,
 450      * you can set the end rule by calling:
 451      * <code>setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2*60*60*1000);</code>
 452      *
 453      * @param endMonth        The daylight saving time ending month. Month is
 454      *                        a {@link Calendar#MONTH MONTH} field
 455      *                        value (0-based. e.g., 9 for October).
 456      * @param endDay          The day of the month on which the daylight saving time ends.
 457      *                        See the class description for the special cases of this parameter.
 458      * @param endDayOfWeek    The daylight saving time ending day-of-week.
 459      *                        See the class description for the special cases of this parameter.
 460      * @param endTime         The daylight saving ending time in local wall clock time,
 461      *                        (in milliseconds within the day) which is local daylight
 462      *                        time in this case.
 463      * @exception IllegalArgumentException if the <code>endMonth</code>, <code>endDay</code>,
 464      * <code>endDayOfWeek</code>, or <code>endTime</code> parameters are out of range
 465      */
 466     public void setEndRule(int endMonth, int endDay, int endDayOfWeek,
 467                            int endTime)
 468     {
 469         this.endMonth = endMonth;
 470         this.endDay = endDay;
 471         this.endDayOfWeek = endDayOfWeek;
 472         this.endTime = endTime;
 473         this.endTimeMode = WALL_TIME;
 474         decodeEndRule();
 475         invalidateCache();
 476     }
 477 
 478     /**
 479      * Sets the daylight saving time end rule to a fixed date within a month.
 480      * This method is equivalent to:
 481      * <pre><code>setEndRule(endMonth, endDay, 0, endTime)</code></pre>
 482      *
 483      * @param endMonth        The daylight saving time ending month. Month is
 484      *                        a {@link Calendar#MONTH MONTH} field
 485      *                        value (0-based. e.g., 9 for October).
 486      * @param endDay          The day of the month on which the daylight saving time ends.
 487      * @param endTime         The daylight saving ending time in local wall clock time,
 488      *                        (in milliseconds within the day) which is local daylight
 489      *                        time in this case.
 490      * @exception IllegalArgumentException the <code>endMonth</code>, <code>endDay</code>,
 491      * or <code>endTime</code> parameters are out of range
 492      * @since 1.2
 493      */
 494     public void setEndRule(int endMonth, int endDay, int endTime)
 495     {
 496         setEndRule(endMonth, endDay, 0, endTime);
 497     }
 498 
 499     /**
 500      * Sets the daylight saving time end rule to a weekday before or after the given date within
 501      * a month, e.g., the first Monday on or after the 8th.
 502      *
 503      * @param endMonth        The daylight saving time ending month. Month is
 504      *                        a {@link Calendar#MONTH MONTH} field
 505      *                        value (0-based. e.g., 9 for October).
 506      * @param endDay          The day of the month on which the daylight saving time ends.
 507      * @param endDayOfWeek    The daylight saving time ending day-of-week.
 508      * @param endTime         The daylight saving ending time in local wall clock time,
 509      *                        (in milliseconds within the day) which is local daylight
 510      *                        time in this case.
 511      * @param after           If true, this rule selects the first <code>endDayOfWeek</code> on
 512      *                        or <em>after</em> <code>endDay</code>.  If false, this rule
 513      *                        selects the last <code>endDayOfWeek</code> on or before
 514      *                        <code>endDay</code> of the month.
 515      * @exception IllegalArgumentException the <code>endMonth</code>, <code>endDay</code>,
 516      * <code>endDayOfWeek</code>, or <code>endTime</code> parameters are out of range
 517      * @since 1.2
 518      */
 519     public void setEndRule(int endMonth, int endDay, int endDayOfWeek, int endTime, boolean after)
 520     {
 521         if (after) {
 522             setEndRule(endMonth, endDay, -endDayOfWeek, endTime);
 523         } else {
 524             setEndRule(endMonth, -endDay, -endDayOfWeek, endTime);
 525         }
 526     }
 527 
 528     /**
 529      * Returns the offset of this time zone from UTC at the given
 530      * time. If daylight saving time is in effect at the given time,
 531      * the offset value is adjusted with the amount of daylight
 532      * saving.
 533      *
 534      * @param date the time at which the time zone offset is found
 535      * @return the amount of time in milliseconds to add to UTC to get
 536      * local time.
 537      * @since 1.4
 538      */
 539     public int getOffset(long date) {
 540         return getOffsets(date, null);
 541     }
 542 
 543     /**
 544      * @see TimeZone#getOffsets
 545      */
 546     int getOffsets(long date, int[] offsets) {
 547         int offset = rawOffset;
 548 
 549       computeOffset:
 550         if (useDaylight) {
 551             Cache cache = this.cache;
 552             if (cache != null) {
 553                 if (date >= cache.start && date < cache.end) {
 554                     offset += dstSavings;
 555                     break computeOffset;
 556                 }
 557             }
 558             BaseCalendar cal = date >= GregorianCalendar.DEFAULT_GREGORIAN_CUTOVER ?
 559                 gcal : (BaseCalendar) CalendarSystem.forName("julian");
 560             BaseCalendar.Date cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE);
 561             // Get the year in local time
 562             cal.getCalendarDate(date + rawOffset, cdate);
 563             int year = cdate.getNormalizedYear();
 564             if (year >= startYear) {
 565                 // Clear time elements for the transition calculations
 566                 cdate.setTimeOfDay(0, 0, 0, 0);
 567                 offset = getOffset(cal, cdate, year, date);
 568             }
 569         }
 570 
 571         if (offsets != null) {
 572             offsets[0] = rawOffset;
 573             offsets[1] = offset - rawOffset;
 574         }
 575         return offset;
 576     }
 577 
 578    /**
 579      * Returns the difference in milliseconds between local time and
 580      * UTC, taking into account both the raw offset and the effect of
 581      * daylight saving, for the specified date and time.  This method
 582      * assumes that the start and end month are distinct.  It also
 583      * uses a default {@link GregorianCalendar} object as its
 584      * underlying calendar, such as for determining leap years.  Do
 585      * not use the result of this method with a calendar other than a
 586      * default <code>GregorianCalendar</code>.
 587      *
 588      * <p><em>Note:  In general, clients should use
 589      * <code>Calendar.get(ZONE_OFFSET) + Calendar.get(DST_OFFSET)</code>
 590      * instead of calling this method.</em>
 591      *
 592      * @param era       The era of the given date.
 593      * @param year      The year in the given date.
 594      * @param month     The month in the given date. Month is 0-based. e.g.,
 595      *                  0 for January.
 596      * @param day       The day-in-month of the given date.
 597      * @param dayOfWeek The day-of-week of the given date.
 598      * @param millis    The milliseconds in day in <em>standard</em> local time.
 599      * @return          The milliseconds to add to UTC to get local time.
 600      * @exception       IllegalArgumentException the <code>era</code>,
 601      *                  <code>month</code>, <code>day</code>, <code>dayOfWeek</code>,
 602      *                  or <code>millis</code> parameters are out of range
 603      */
 604     public int getOffset(int era, int year, int month, int day, int dayOfWeek,
 605                          int millis)
 606     {
 607         if (era != GregorianCalendar.AD && era != GregorianCalendar.BC) {
 608             throw new IllegalArgumentException("Illegal era " + era);
 609         }
 610 
 611         int y = year;
 612         if (era == GregorianCalendar.BC) {
 613             // adjust y with the GregorianCalendar-style year numbering.
 614             y = 1 - y;
 615         }
 616 
 617         // If the year isn't representable with the 64-bit long
 618         // integer in milliseconds, convert the year to an
 619         // equivalent year. This is required to pass some JCK test cases
 620         // which are actually useless though because the specified years
 621         // can't be supported by the Java time system.
 622         if (y >= 292278994) {
 623             y = 2800 + y % 2800;
 624         } else if (y <= -292269054) {
 625             // y %= 28 also produces an equivalent year, but positive
 626             // year numbers would be convenient to use the UNIX cal
 627             // command.
 628             y = (int) CalendarUtils.mod((long) y, 28);
 629         }
 630 
 631         // convert year to its 1-based month value
 632         int m = month + 1;
 633 
 634         // First, calculate time as a Gregorian date.
 635         BaseCalendar cal = gcal;
 636         BaseCalendar.Date cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE);
 637         cdate.setDate(y, m, day);
 638         long time = cal.getTime(cdate); // normalize cdate
 639         time += millis - rawOffset; // UTC time
 640 
 641         // If the time value represents a time before the default
 642         // Gregorian cutover, recalculate time using the Julian
 643         // calendar system. For the Julian calendar system, the
 644         // normalized year numbering is ..., -2 (BCE 2), -1 (BCE 1),
 645         // 1, 2 ... which is different from the GregorianCalendar
 646         // style year numbering (..., -1, 0 (BCE 1), 1, 2, ...).
 647         if (time < GregorianCalendar.DEFAULT_GREGORIAN_CUTOVER) {
 648             cal = (BaseCalendar) CalendarSystem.forName("julian");
 649             cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE);
 650             cdate.setNormalizedDate(y, m, day);
 651             time = cal.getTime(cdate) + millis - rawOffset;
 652         }
 653 
 654         if ((cdate.getNormalizedYear() != y)
 655             || (cdate.getMonth() != m)
 656             || (cdate.getDayOfMonth() != day)
 657             // The validation should be cdate.getDayOfWeek() ==
 658             // dayOfWeek. However, we don't check dayOfWeek for
 659             // compatibility.
 660             || (dayOfWeek < Calendar.SUNDAY || dayOfWeek > Calendar.SATURDAY)
 661             || (millis < 0 || millis >= (24*60*60*1000))) {
 662             throw new IllegalArgumentException();
 663         }
 664 
 665         if (!useDaylight || year < startYear || era != GregorianCalendar.CE) {
 666             return rawOffset;
 667         }
 668 
 669         return getOffset(cal, cdate, y, time);
 670     }
 671 
 672     private int getOffset(BaseCalendar cal, BaseCalendar.Date cdate, int year, long time) {
 673         Cache cache = this.cache;
 674         if (cache != null) {
 675             if (time >= cache.start && time < cache.end) {
 676                 return rawOffset + dstSavings;
 677             }
 678             if (year == cache.year) {
 679                 return rawOffset;
 680             }
 681         }
 682 
 683         long start = getStart(cal, cdate, year);
 684         long end = getEnd(cal, cdate, year);
 685         int offset = rawOffset;
 686         if (start <= end) {
 687             if (time >= start && time < end) {
 688                 offset += dstSavings;
 689             }
 690             this.cache = new Cache(year, start, end);
 691         } else {
 692             if (time < end) {
 693                 // TODO: support Gregorian cutover. The previous year
 694                 // may be in the other calendar system.
 695                 start = getStart(cal, cdate, year - 1);
 696                 if (time >= start) {
 697                     offset += dstSavings;
 698                 }
 699             } else if (time >= start) {
 700                 // TODO: support Gregorian cutover. The next year
 701                 // may be in the other calendar system.
 702                 end = getEnd(cal, cdate, year + 1);
 703                 if (time < end) {
 704                     offset += dstSavings;
 705                 }
 706             }
 707             if (start <= end) {
 708                 this.cache = new Cache((long) startYear - 1, start, end);
 709             }
 710         }
 711         return offset;
 712     }
 713 
 714     private long getStart(BaseCalendar cal, BaseCalendar.Date cdate, int year) {
 715         int time = startTime;
 716         if (startTimeMode != UTC_TIME) {
 717             time -= rawOffset;
 718         }
 719         return getTransition(cal, cdate, startMode, year, startMonth, startDay,
 720                              startDayOfWeek, time);
 721     }
 722 
 723     private long getEnd(BaseCalendar cal, BaseCalendar.Date cdate, int year) {
 724         int time = endTime;
 725         if (endTimeMode != UTC_TIME) {
 726             time -= rawOffset;
 727         }
 728         if (endTimeMode == WALL_TIME) {
 729             time -= dstSavings;
 730         }
 731         return getTransition(cal, cdate, endMode, year, endMonth, endDay,
 732                                         endDayOfWeek, time);
 733     }
 734 
 735     private long getTransition(BaseCalendar cal, BaseCalendar.Date cdate,
 736                                int mode, int year, int month, int dayOfMonth,
 737                                int dayOfWeek, int timeOfDay) {
 738         cdate.setNormalizedYear(year);
 739         cdate.setMonth(month + 1);
 740         switch (mode) {
 741         case DOM_MODE:
 742             cdate.setDayOfMonth(dayOfMonth);
 743             break;
 744 
 745         case DOW_IN_MONTH_MODE:
 746             cdate.setDayOfMonth(1);
 747             if (dayOfMonth < 0) {
 748                 cdate.setDayOfMonth(cal.getMonthLength(cdate));
 749             }
 750             cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(dayOfMonth, dayOfWeek, cdate);
 751             break;
 752 
 753         case DOW_GE_DOM_MODE:
 754             cdate.setDayOfMonth(dayOfMonth);
 755             cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(1, dayOfWeek, cdate);
 756             break;
 757 
 758         case DOW_LE_DOM_MODE:
 759             cdate.setDayOfMonth(dayOfMonth);
 760             cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(-1, dayOfWeek, cdate);
 761             break;
 762         }
 763         return cal.getTime(cdate) + timeOfDay;
 764     }
 765 
 766     /**
 767      * Gets the GMT offset for this time zone.
 768      * @return the GMT offset value in milliseconds
 769      * @see #setRawOffset
 770      */
 771     public int getRawOffset()
 772     {
 773         // The given date will be taken into account while
 774         // we have the historical time zone data in place.
 775         return rawOffset;
 776     }
 777 
 778     /**
 779      * Sets the base time zone offset to GMT.
 780      * This is the offset to add to UTC to get local time.
 781      * @see #getRawOffset
 782      */
 783     public void setRawOffset(int offsetMillis)
 784     {
 785         this.rawOffset = offsetMillis;
 786     }
 787 
 788     /**
 789      * Sets the amount of time in milliseconds that the clock is advanced
 790      * during daylight saving time.
 791      * @param millisSavedDuringDST the number of milliseconds the time is
 792      * advanced with respect to standard time when the daylight saving time rules
 793      * are in effect. A positive number, typically one hour (3600000).
 794      * @see #getDSTSavings
 795      * @since 1.2
 796      */
 797     public void setDSTSavings(int millisSavedDuringDST) {
 798         if (millisSavedDuringDST <= 0) {
 799             throw new IllegalArgumentException("Illegal daylight saving value: "
 800                                                + millisSavedDuringDST);
 801         }
 802         dstSavings = millisSavedDuringDST;
 803     }
 804 
 805     /**
 806      * Returns the amount of time in milliseconds that the clock is
 807      * advanced during daylight saving time.
 808      *
 809      * @return the number of milliseconds the time is advanced with
 810      * respect to standard time when the daylight saving rules are in
 811      * effect, or 0 (zero) if this time zone doesn't observe daylight
 812      * saving time.
 813      *
 814      * @see #setDSTSavings
 815      * @since 1.2
 816      */
 817     public int getDSTSavings() {
 818         return useDaylight ? dstSavings : 0;
 819     }
 820 
 821     /**
 822      * Queries if this time zone uses daylight saving time.
 823      * @return true if this time zone uses daylight saving time;
 824      * false otherwise.
 825      */
 826     public boolean useDaylightTime()
 827     {
 828         return useDaylight;
 829     }
 830 
 831     /**
 832      * Returns {@code true} if this {@code SimpleTimeZone} observes
 833      * Daylight Saving Time. This method is equivalent to {@link
 834      * #useDaylightTime()}.
 835      *
 836      * @return {@code true} if this {@code SimpleTimeZone} observes
 837      * Daylight Saving Time; {@code false} otherwise.
 838      * @since 1.7
 839      */
 840     @Override
 841     public boolean observesDaylightTime() {
 842         return useDaylightTime();
 843     }
 844 
 845     /**
 846      * Queries if the given date is in daylight saving time.
 847      * @return true if daylight saving time is in effective at the
 848      * given date; false otherwise.
 849      */
 850     public boolean inDaylightTime(Date date)
 851     {
 852         return (getOffset(date.getTime()) != rawOffset);
 853     }
 854 
 855     /**
 856      * Returns a clone of this <code>SimpleTimeZone</code> instance.
 857      * @return a clone of this instance.
 858      */
 859     public Object clone()
 860     {
 861         return super.clone();
 862     }
 863 
 864     /**
 865      * Generates the hash code for the SimpleDateFormat object.
 866      * @return the hash code for this object
 867      */
 868     public int hashCode()
 869     {
 870         return startMonth ^ startDay ^ startDayOfWeek ^ startTime ^
 871             endMonth ^ endDay ^ endDayOfWeek ^ endTime ^ rawOffset;
 872     }
 873 
 874     /**
 875      * Compares the equality of two <code>SimpleTimeZone</code> objects.
 876      *
 877      * @param obj  The <code>SimpleTimeZone</code> object to be compared with.
 878      * @return     True if the given <code>obj</code> is the same as this
 879      *             <code>SimpleTimeZone</code> object; false otherwise.
 880      */
 881     public boolean equals(Object obj)
 882     {
 883         if (this == obj) {
 884             return true;
 885         }
 886         if (!(obj instanceof SimpleTimeZone)) {
 887             return false;
 888         }
 889 
 890         SimpleTimeZone that = (SimpleTimeZone) obj;
 891 
 892         return getID().equals(that.getID()) &&
 893             hasSameRules(that);
 894     }
 895 
 896     /**
 897      * Returns <code>true</code> if this zone has the same rules and offset as another zone.
 898      * @param other the TimeZone object to be compared with
 899      * @return <code>true</code> if the given zone is a SimpleTimeZone and has the
 900      * same rules and offset as this one
 901      * @since 1.2
 902      */
 903     public boolean hasSameRules(TimeZone other) {
 904         if (this == other) {
 905             return true;
 906         }
 907         if (!(other instanceof SimpleTimeZone)) {
 908             return false;
 909         }
 910         SimpleTimeZone that = (SimpleTimeZone) other;
 911         return rawOffset == that.rawOffset &&
 912             useDaylight == that.useDaylight &&
 913             (!useDaylight
 914              // Only check rules if using DST
 915              || (dstSavings == that.dstSavings &&
 916                  startMode == that.startMode &&
 917                  startMonth == that.startMonth &&
 918                  startDay == that.startDay &&
 919                  startDayOfWeek == that.startDayOfWeek &&
 920                  startTime == that.startTime &&
 921                  startTimeMode == that.startTimeMode &&
 922                  endMode == that.endMode &&
 923                  endMonth == that.endMonth &&
 924                  endDay == that.endDay &&
 925                  endDayOfWeek == that.endDayOfWeek &&
 926                  endTime == that.endTime &&
 927                  endTimeMode == that.endTimeMode &&
 928                  startYear == that.startYear));
 929     }
 930 
 931     /**
 932      * Returns a string representation of this time zone.
 933      * @return a string representation of this time zone.
 934      */
 935     public String toString() {
 936         return getClass().getName() +
 937             "[id=" + getID() +
 938             ",offset=" + rawOffset +
 939             ",dstSavings=" + dstSavings +
 940             ",useDaylight=" + useDaylight +
 941             ",startYear=" + startYear +
 942             ",startMode=" + startMode +
 943             ",startMonth=" + startMonth +
 944             ",startDay=" + startDay +
 945             ",startDayOfWeek=" + startDayOfWeek +
 946             ",startTime=" + startTime +
 947             ",startTimeMode=" + startTimeMode +
 948             ",endMode=" + endMode +
 949             ",endMonth=" + endMonth +
 950             ",endDay=" + endDay +
 951             ",endDayOfWeek=" + endDayOfWeek +
 952             ",endTime=" + endTime +
 953             ",endTimeMode=" + endTimeMode + ']';
 954     }
 955 
 956     // =======================privates===============================
 957 
 958     /**
 959      * The month in which daylight saving time starts.  This value must be
 960      * between <code>Calendar.JANUARY</code> and
 961      * <code>Calendar.DECEMBER</code> inclusive.  This value must not equal
 962      * <code>endMonth</code>.
 963      * <p>If <code>useDaylight</code> is false, this value is ignored.
 964      * @serial
 965      */
 966     private int startMonth;
 967 
 968     /**
 969      * This field has two possible interpretations:
 970      * <dl>
 971      * <dt><code>startMode == DOW_IN_MONTH</code></dt>
 972      * <dd>
 973      * <code>startDay</code> indicates the day of the month of
 974      * <code>startMonth</code> on which daylight
 975      * saving time starts, from 1 to 28, 30, or 31, depending on the
 976      * <code>startMonth</code>.
 977      * </dd>
 978      * <dt><code>startMode != DOW_IN_MONTH</code></dt>
 979      * <dd>
 980      * <code>startDay</code> indicates which <code>startDayOfWeek</code> in the
 981      * month <code>startMonth</code> daylight
 982      * saving time starts on.  For example, a value of +1 and a
 983      * <code>startDayOfWeek</code> of <code>Calendar.SUNDAY</code> indicates the
 984      * first Sunday of <code>startMonth</code>.  Likewise, +2 would indicate the
 985      * second Sunday, and -1 the last Sunday.  A value of 0 is illegal.
 986      * </dd>
 987      * </dl>
 988      * <p>If <code>useDaylight</code> is false, this value is ignored.
 989      * @serial
 990      */
 991     private int startDay;
 992 
 993     /**
 994      * The day of the week on which daylight saving time starts.  This value
 995      * must be between <code>Calendar.SUNDAY</code> and
 996      * <code>Calendar.SATURDAY</code> inclusive.
 997      * <p>If <code>useDaylight</code> is false or
 998      * <code>startMode == DAY_OF_MONTH</code>, this value is ignored.
 999      * @serial
1000      */
1001     private int startDayOfWeek;
1002 
1003     /**
1004      * The time in milliseconds after midnight at which daylight saving
1005      * time starts.  This value is expressed as wall time, standard time,
1006      * or UTC time, depending on the setting of <code>startTimeMode</code>.
1007      * <p>If <code>useDaylight</code> is false, this value is ignored.
1008      * @serial
1009      */
1010     private int startTime;
1011 
1012     /**
1013      * The format of startTime, either WALL_TIME, STANDARD_TIME, or UTC_TIME.
1014      * @serial
1015      * @since 1.3
1016      */
1017     private int startTimeMode;
1018 
1019     /**
1020      * The month in which daylight saving time ends.  This value must be
1021      * between <code>Calendar.JANUARY</code> and
1022      * <code>Calendar.UNDECIMBER</code>.  This value must not equal
1023      * <code>startMonth</code>.
1024      * <p>If <code>useDaylight</code> is false, this value is ignored.
1025      * @serial
1026      */
1027     private int endMonth;
1028 
1029     /**
1030      * This field has two possible interpretations:
1031      * <dl>
1032      * <dt><code>endMode == DOW_IN_MONTH</code></dt>
1033      * <dd>
1034      * <code>endDay</code> indicates the day of the month of
1035      * <code>endMonth</code> on which daylight
1036      * saving time ends, from 1 to 28, 30, or 31, depending on the
1037      * <code>endMonth</code>.
1038      * </dd>
1039      * <dt><code>endMode != DOW_IN_MONTH</code></dt>
1040      * <dd>
1041      * <code>endDay</code> indicates which <code>endDayOfWeek</code> in th
1042      * month <code>endMonth</code> daylight
1043      * saving time ends on.  For example, a value of +1 and a
1044      * <code>endDayOfWeek</code> of <code>Calendar.SUNDAY</code> indicates the
1045      * first Sunday of <code>endMonth</code>.  Likewise, +2 would indicate the
1046      * second Sunday, and -1 the last Sunday.  A value of 0 is illegal.
1047      * </dd>
1048      * </dl>
1049      * <p>If <code>useDaylight</code> is false, this value is ignored.
1050      * @serial
1051      */
1052     private int endDay;
1053 
1054     /**
1055      * The day of the week on which daylight saving time ends.  This value
1056      * must be between <code>Calendar.SUNDAY</code> and
1057      * <code>Calendar.SATURDAY</code> inclusive.
1058      * <p>If <code>useDaylight</code> is false or
1059      * <code>endMode == DAY_OF_MONTH</code>, this value is ignored.
1060      * @serial
1061      */
1062     private int endDayOfWeek;
1063 
1064     /**
1065      * The time in milliseconds after midnight at which daylight saving
1066      * time ends.  This value is expressed as wall time, standard time,
1067      * or UTC time, depending on the setting of <code>endTimeMode</code>.
1068      * <p>If <code>useDaylight</code> is false, this value is ignored.
1069      * @serial
1070      */
1071     private int endTime;
1072 
1073     /**
1074      * The format of endTime, either <code>WALL_TIME</code>,
1075      * <code>STANDARD_TIME</code>, or <code>UTC_TIME</code>.
1076      * @serial
1077      * @since 1.3
1078      */
1079     private int endTimeMode;
1080 
1081     /**
1082      * The year in which daylight saving time is first observed.  This is an {@link GregorianCalendar#AD AD}
1083      * value.  If this value is less than 1 then daylight saving time is observed
1084      * for all <code>AD</code> years.
1085      * <p>If <code>useDaylight</code> is false, this value is ignored.
1086      * @serial
1087      */
1088     private int startYear;
1089 
1090     /**
1091      * The offset in milliseconds between this zone and GMT.  Negative offsets
1092      * are to the west of Greenwich.  To obtain local <em>standard</em> time,
1093      * add the offset to GMT time.  To obtain local wall time it may also be
1094      * necessary to add <code>dstSavings</code>.
1095      * @serial
1096      */
1097     private int rawOffset;
1098 
1099     /**
1100      * A boolean value which is true if and only if this zone uses daylight
1101      * saving time.  If this value is false, several other fields are ignored.
1102      * @serial
1103      */
1104     private boolean useDaylight=false; // indicate if this time zone uses DST
1105 
1106     private static final int millisPerHour = 60*60*1000;
1107     private static final int millisPerDay  = 24*millisPerHour;
1108 
1109     /**
1110      * This field was serialized in JDK 1.1, so we have to keep it that way
1111      * to maintain serialization compatibility. However, there's no need to
1112      * recreate the array each time we create a new time zone.
1113      * @serial An array of bytes containing the values {31, 28, 31, 30, 31, 30,
1114      * 31, 31, 30, 31, 30, 31}.  This is ignored as of the Java 2 platform v1.2, however, it must
1115      * be streamed out for compatibility with JDK 1.1.
1116      */
1117     private final byte[] monthLength = staticMonthLength;
1118     private static final byte[] staticMonthLength = {31,28,31,30,31,30,31,31,30,31,30,31};
1119     private static final byte[] staticLeapMonthLength = {31,29,31,30,31,30,31,31,30,31,30,31};
1120 
1121     /**
1122      * Variables specifying the mode of the start rule.  Takes the following
1123      * values:
1124      * <dl>
1125      * <dt><code>DOM_MODE</code></dt>
1126      * <dd>
1127      * Exact day of week; e.g., March 1.
1128      * </dd>
1129      * <dt><code>DOW_IN_MONTH_MODE</code></dt>
1130      * <dd>
1131      * Day of week in month; e.g., last Sunday in March.
1132      * </dd>
1133      * <dt><code>DOW_GE_DOM_MODE</code></dt>
1134      * <dd>
1135      * Day of week after day of month; e.g., Sunday on or after March 15.
1136      * </dd>
1137      * <dt><code>DOW_LE_DOM_MODE</code></dt>
1138      * <dd>
1139      * Day of week before day of month; e.g., Sunday on or before March 15.
1140      * </dd>
1141      * </dl>
1142      * The setting of this field affects the interpretation of the
1143      * <code>startDay</code> field.
1144      * <p>If <code>useDaylight</code> is false, this value is ignored.
1145      * @serial
1146      * @since 1.1.4
1147      */
1148     private int startMode;
1149 
1150     /**
1151      * Variables specifying the mode of the end rule.  Takes the following
1152      * values:
1153      * <dl>
1154      * <dt><code>DOM_MODE</code></dt>
1155      * <dd>
1156      * Exact day of week; e.g., March 1.
1157      * </dd>
1158      * <dt><code>DOW_IN_MONTH_MODE</code></dt>
1159      * <dd>
1160      * Day of week in month; e.g., last Sunday in March.
1161      * </dd>
1162      * <dt><code>DOW_GE_DOM_MODE</code></dt>
1163      * <dd>
1164      * Day of week after day of month; e.g., Sunday on or after March 15.
1165      * </dd>
1166      * <dt><code>DOW_LE_DOM_MODE</code></dt>
1167      * <dd>
1168      * Day of week before day of month; e.g., Sunday on or before March 15.
1169      * </dd>
1170      * </dl>
1171      * The setting of this field affects the interpretation of the
1172      * <code>endDay</code> field.
1173      * <p>If <code>useDaylight</code> is false, this value is ignored.
1174      * @serial
1175      * @since 1.1.4
1176      */
1177     private int endMode;
1178 
1179     /**
1180      * A positive value indicating the amount of time saved during DST in
1181      * milliseconds.
1182      * Typically one hour (3600000); sometimes 30 minutes (1800000).
1183      * <p>If <code>useDaylight</code> is false, this value is ignored.
1184      * @serial
1185      * @since 1.1.4
1186      */
1187     private int dstSavings;
1188 
1189     private static final Gregorian gcal = CalendarSystem.getGregorianCalendar();
1190 
1191     /**
1192      * Cache values representing a single period of daylight saving
1193      * time. Cache.start is the start time (inclusive) of daylight
1194      * saving time and Cache.end is the end time (exclusive).
1195      *
1196      * Cache.year has a year value if both Cache.start and Cache.end are
1197      * in the same year. Cache.year is set to startYear - 1 if
1198      * Cache.start and Cache.end are in different years.
1199      * Cache.year is a long to support Integer.MIN_VALUE - 1 (JCK requirement).
1200      */
1201     private static final class Cache {
1202         final long year;
1203         final long start;
1204         final long end;
1205 
1206         Cache(long year, long start, long end) {
1207             this.year = year;
1208             this.start = start;
1209             this.end = end;
1210         }
1211     }
1212 
1213     private transient volatile Cache cache;
1214 
1215     /**
1216      * Constants specifying values of startMode and endMode.
1217      */
1218     private static final int DOM_MODE          = 1; // Exact day of month, "Mar 1"
1219     private static final int DOW_IN_MONTH_MODE = 2; // Day of week in month, "lastSun"
1220     private static final int DOW_GE_DOM_MODE   = 3; // Day of week after day of month, "Sun>=15"
1221     private static final int DOW_LE_DOM_MODE   = 4; // Day of week before day of month, "Sun<=21"
1222 
1223     /**
1224      * Constant for a mode of start or end time specified as wall clock
1225      * time.  Wall clock time is standard time for the onset rule, and
1226      * daylight time for the end rule.
1227      * @since 1.4
1228      */
1229     public static final int WALL_TIME = 0; // Zero for backward compatibility
1230 
1231     /**
1232      * Constant for a mode of start or end time specified as standard time.
1233      * @since 1.4
1234      */
1235     public static final int STANDARD_TIME = 1;
1236 
1237     /**
1238      * Constant for a mode of start or end time specified as UTC. European
1239      * Union rules are specified as UTC time, for example.
1240      * @since 1.4
1241      */
1242     public static final int UTC_TIME = 2;
1243 
1244     // Proclaim compatibility with 1.1
1245     static final long serialVersionUID = -403250971215465050L;
1246 
1247     // the internal serial version which says which version was written
1248     // - 0 (default) for version up to JDK 1.1.3
1249     // - 1 for version from JDK 1.1.4, which includes 3 new fields
1250     // - 2 for JDK 1.3, which includes 2 new fields
1251     static final int currentSerialVersion = 2;
1252 
1253     /**
1254      * The version of the serialized data on the stream.  Possible values:
1255      * <dl>
1256      * <dt><b>0</b> or not present on stream</dt>
1257      * <dd>
1258      * JDK 1.1.3 or earlier.
1259      * </dd>
1260      * <dt><b>1</b></dt>
1261      * <dd>
1262      * JDK 1.1.4 or later.  Includes three new fields: <code>startMode</code>,
1263      * <code>endMode</code>, and <code>dstSavings</code>.
1264      * </dd>
1265      * <dt><b>2</b></dt>
1266      * <dd>
1267      * JDK 1.3 or later.  Includes two new fields: <code>startTimeMode</code>
1268      * and <code>endTimeMode</code>.
1269      * </dd>
1270      * </dl>
1271      * When streaming out this class, the most recent format
1272      * and the highest allowable <code>serialVersionOnStream</code>
1273      * is written.
1274      * @serial
1275      * @since 1.1.4
1276      */
1277     private int serialVersionOnStream = currentSerialVersion;
1278 
1279     // Maximum number of rules.
1280     private static final int MAX_RULE_NUM = 6;
1281 
1282     private void invalidateCache() {
1283         cache = null;
1284     }
1285 
1286     //----------------------------------------------------------------------
1287     // Rule representation
1288     //
1289     // We represent the following flavors of rules:
1290     //       5        the fifth of the month
1291     //       lastSun  the last Sunday in the month
1292     //       lastMon  the last Monday in the month
1293     //       Sun>=8   first Sunday on or after the eighth
1294     //       Sun<=25  last Sunday on or before the 25th
1295     // This is further complicated by the fact that we need to remain
1296     // backward compatible with the 1.1 FCS.  Finally, we need to minimize
1297     // API changes.  In order to satisfy these requirements, we support
1298     // three representation systems, and we translate between them.
1299     //
1300     // INTERNAL REPRESENTATION
1301     // This is the format SimpleTimeZone objects take after construction or
1302     // streaming in is complete.  Rules are represented directly, using an
1303     // unencoded format.  We will discuss the start rule only below; the end
1304     // rule is analogous.
1305     //   startMode      Takes on enumerated values DAY_OF_MONTH,
1306     //                  DOW_IN_MONTH, DOW_AFTER_DOM, or DOW_BEFORE_DOM.
1307     //   startDay       The day of the month, or for DOW_IN_MONTH mode, a
1308     //                  value indicating which DOW, such as +1 for first,
1309     //                  +2 for second, -1 for last, etc.
1310     //   startDayOfWeek The day of the week.  Ignored for DAY_OF_MONTH.
1311     //
1312     // ENCODED REPRESENTATION
1313     // This is the format accepted by the constructor and by setStartRule()
1314     // and setEndRule().  It uses various combinations of positive, negative,
1315     // and zero values to encode the different rules.  This representation
1316     // allows us to specify all the different rule flavors without altering
1317     // the API.
1318     //   MODE              startMonth    startDay    startDayOfWeek
1319     //   DOW_IN_MONTH_MODE >=0           !=0         >0
1320     //   DOM_MODE          >=0           >0          ==0
1321     //   DOW_GE_DOM_MODE   >=0           >0          <0
1322     //   DOW_LE_DOM_MODE   >=0           <0          <0
1323     //   (no DST)          don't care    ==0         don't care
1324     //
1325     // STREAMED REPRESENTATION
1326     // We must retain binary compatibility with the 1.1 FCS.  The 1.1 code only
1327     // handles DOW_IN_MONTH_MODE and non-DST mode, the latter indicated by the
1328     // flag useDaylight.  When we stream an object out, we translate into an
1329     // approximate DOW_IN_MONTH_MODE representation so the object can be parsed
1330     // and used by 1.1 code.  Following that, we write out the full
1331     // representation separately so that contemporary code can recognize and
1332     // parse it.  The full representation is written in a "packed" format,
1333     // consisting of a version number, a length, and an array of bytes.  Future
1334     // versions of this class may specify different versions.  If they wish to
1335     // include additional data, they should do so by storing them after the
1336     // packed representation below.
1337     //----------------------------------------------------------------------
1338 
1339     /**
1340      * Given a set of encoded rules in startDay and startDayOfMonth, decode
1341      * them and set the startMode appropriately.  Do the same for endDay and
1342      * endDayOfMonth.  Upon entry, the day of week variables may be zero or
1343      * negative, in order to indicate special modes.  The day of month
1344      * variables may also be negative.  Upon exit, the mode variables will be
1345      * set, and the day of week and day of month variables will be positive.
1346      * This method also recognizes a startDay or endDay of zero as indicating
1347      * no DST.
1348      */
1349     private void decodeRules()
1350     {
1351         decodeStartRule();
1352         decodeEndRule();
1353     }
1354 
1355     /**
1356      * Decode the start rule and validate the parameters.  The parameters are
1357      * expected to be in encoded form, which represents the various rule modes
1358      * by negating or zeroing certain values.  Representation formats are:
1359      * <p>
1360      * <pre>
1361      *            DOW_IN_MONTH  DOM    DOW>=DOM  DOW<=DOM  no DST
1362      *            ------------  -----  --------  --------  ----------
1363      * month       0..11        same    same      same     don't care
1364      * day        -5..5         1..31   1..31    -1..-31   0
1365      * dayOfWeek   1..7         0      -1..-7    -1..-7    don't care
1366      * time        0..ONEDAY    same    same      same     don't care
1367      * </pre>
1368      * The range for month does not include UNDECIMBER since this class is
1369      * really specific to GregorianCalendar, which does not use that month.
1370      * The range for time includes ONEDAY (vs. ending at ONEDAY-1) because the
1371      * end rule is an exclusive limit point.  That is, the range of times that
1372      * are in DST include those >= the start and < the end.  For this reason,
1373      * it should be possible to specify an end of ONEDAY in order to include the
1374      * entire day.  Although this is equivalent to time 0 of the following day,
1375      * it's not always possible to specify that, for example, on December 31.
1376      * While arguably the start range should still be 0..ONEDAY-1, we keep
1377      * the start and end ranges the same for consistency.
1378      */
1379     private void decodeStartRule() {
1380         useDaylight = (startDay != 0) && (endDay != 0);
1381         if (startDay != 0) {
1382             if (startMonth < Calendar.JANUARY || startMonth > Calendar.DECEMBER) {
1383                 throw new IllegalArgumentException(
1384                         "Illegal start month " + startMonth);
1385             }
1386             if (startTime < 0 || startTime > millisPerDay) {
1387                 throw new IllegalArgumentException(
1388                         "Illegal start time " + startTime);
1389             }
1390             if (startDayOfWeek == 0) {
1391                 startMode = DOM_MODE;
1392             } else {
1393                 if (startDayOfWeek > 0) {
1394                     startMode = DOW_IN_MONTH_MODE;
1395                 } else {
1396                     startDayOfWeek = -startDayOfWeek;
1397                     if (startDay > 0) {
1398                         startMode = DOW_GE_DOM_MODE;
1399                     } else {
1400                         startDay = -startDay;
1401                         startMode = DOW_LE_DOM_MODE;
1402                     }
1403                 }
1404                 if (startDayOfWeek > Calendar.SATURDAY) {
1405                     throw new IllegalArgumentException(
1406                            "Illegal start day of week " + startDayOfWeek);
1407                 }
1408             }
1409             if (startMode == DOW_IN_MONTH_MODE) {
1410                 if (startDay < -5 || startDay > 5) {
1411                     throw new IllegalArgumentException(
1412                             "Illegal start day of week in month " + startDay);
1413                 }
1414             } else if (startDay < 1 || startDay > staticMonthLength[startMonth]) {
1415                 throw new IllegalArgumentException(
1416                         "Illegal start day " + startDay);
1417             }
1418         }
1419     }
1420 
1421     /**
1422      * Decode the end rule and validate the parameters.  This method is exactly
1423      * analogous to decodeStartRule().
1424      * @see decodeStartRule
1425      */
1426     private void decodeEndRule() {
1427         useDaylight = (startDay != 0) && (endDay != 0);
1428         if (endDay != 0) {
1429             if (endMonth < Calendar.JANUARY || endMonth > Calendar.DECEMBER) {
1430                 throw new IllegalArgumentException(
1431                         "Illegal end month " + endMonth);
1432             }
1433             if (endTime < 0 || endTime > millisPerDay) {
1434                 throw new IllegalArgumentException(
1435                         "Illegal end time " + endTime);
1436             }
1437             if (endDayOfWeek == 0) {
1438                 endMode = DOM_MODE;
1439             } else {
1440                 if (endDayOfWeek > 0) {
1441                     endMode = DOW_IN_MONTH_MODE;
1442                 } else {
1443                     endDayOfWeek = -endDayOfWeek;
1444                     if (endDay > 0) {
1445                         endMode = DOW_GE_DOM_MODE;
1446                     } else {
1447                         endDay = -endDay;
1448                         endMode = DOW_LE_DOM_MODE;
1449                     }
1450                 }
1451                 if (endDayOfWeek > Calendar.SATURDAY) {
1452                     throw new IllegalArgumentException(
1453                            "Illegal end day of week " + endDayOfWeek);
1454                 }
1455             }
1456             if (endMode == DOW_IN_MONTH_MODE) {
1457                 if (endDay < -5 || endDay > 5) {
1458                     throw new IllegalArgumentException(
1459                             "Illegal end day of week in month " + endDay);
1460                 }
1461             } else if (endDay < 1 || endDay > staticMonthLength[endMonth]) {
1462                 throw new IllegalArgumentException(
1463                         "Illegal end day " + endDay);
1464             }
1465         }
1466     }
1467 
1468     /**
1469      * Make rules compatible to 1.1 FCS code.  Since 1.1 FCS code only understands
1470      * day-of-week-in-month rules, we must modify other modes of rules to their
1471      * approximate equivalent in 1.1 FCS terms.  This method is used when streaming
1472      * out objects of this class.  After it is called, the rules will be modified,
1473      * with a possible loss of information.  startMode and endMode will NOT be
1474      * altered, even though semantically they should be set to DOW_IN_MONTH_MODE,
1475      * since the rule modification is only intended to be temporary.
1476      */
1477     private void makeRulesCompatible()
1478     {
1479         switch (startMode) {
1480         case DOM_MODE:
1481             startDay = 1 + (startDay / 7);
1482             startDayOfWeek = Calendar.SUNDAY;
1483             break;
1484 
1485         case DOW_GE_DOM_MODE:
1486             // A day-of-month of 1 is equivalent to DOW_IN_MONTH_MODE
1487             // that is, Sun>=1 == firstSun.
1488             if (startDay != 1) {
1489                 startDay = 1 + (startDay / 7);
1490             }
1491             break;
1492 
1493         case DOW_LE_DOM_MODE:
1494             if (startDay >= 30) {
1495                 startDay = -1;
1496             } else {
1497                 startDay = 1 + (startDay / 7);
1498             }
1499             break;
1500         }
1501 
1502         switch (endMode) {
1503         case DOM_MODE:
1504             endDay = 1 + (endDay / 7);
1505             endDayOfWeek = Calendar.SUNDAY;
1506             break;
1507 
1508         case DOW_GE_DOM_MODE:
1509             // A day-of-month of 1 is equivalent to DOW_IN_MONTH_MODE
1510             // that is, Sun>=1 == firstSun.
1511             if (endDay != 1) {
1512                 endDay = 1 + (endDay / 7);
1513             }
1514             break;
1515 
1516         case DOW_LE_DOM_MODE:
1517             if (endDay >= 30) {
1518                 endDay = -1;
1519             } else {
1520                 endDay = 1 + (endDay / 7);
1521             }
1522             break;
1523         }
1524 
1525         /*
1526          * Adjust the start and end times to wall time.  This works perfectly
1527          * well unless it pushes into the next or previous day.  If that
1528          * happens, we attempt to adjust the day rule somewhat crudely.  The day
1529          * rules have been forced into DOW_IN_MONTH mode already, so we change
1530          * the day of week to move forward or back by a day.  It's possible to
1531          * make a more refined adjustment of the original rules first, but in
1532          * most cases this extra effort will go to waste once we adjust the day
1533          * rules anyway.
1534          */
1535         switch (startTimeMode) {
1536         case UTC_TIME:
1537             startTime += rawOffset;
1538             break;
1539         }
1540         while (startTime < 0) {
1541             startTime += millisPerDay;
1542             startDayOfWeek = 1 + ((startDayOfWeek+5) % 7); // Back 1 day
1543         }
1544         while (startTime >= millisPerDay) {
1545             startTime -= millisPerDay;
1546             startDayOfWeek = 1 + (startDayOfWeek % 7); // Forward 1 day
1547         }
1548 
1549         switch (endTimeMode) {
1550         case UTC_TIME:
1551             endTime += rawOffset + dstSavings;
1552             break;
1553         case STANDARD_TIME:
1554             endTime += dstSavings;
1555         }
1556         while (endTime < 0) {
1557             endTime += millisPerDay;
1558             endDayOfWeek = 1 + ((endDayOfWeek+5) % 7); // Back 1 day
1559         }
1560         while (endTime >= millisPerDay) {
1561             endTime -= millisPerDay;
1562             endDayOfWeek = 1 + (endDayOfWeek % 7); // Forward 1 day
1563         }
1564     }
1565 
1566     /**
1567      * Pack the start and end rules into an array of bytes.  Only pack
1568      * data which is not preserved by makeRulesCompatible.
1569      */
1570     private byte[] packRules()
1571     {
1572         byte[] rules = new byte[MAX_RULE_NUM];
1573         rules[0] = (byte)startDay;
1574         rules[1] = (byte)startDayOfWeek;
1575         rules[2] = (byte)endDay;
1576         rules[3] = (byte)endDayOfWeek;
1577 
1578         // As of serial version 2, include time modes
1579         rules[4] = (byte)startTimeMode;
1580         rules[5] = (byte)endTimeMode;
1581 
1582         return rules;
1583     }
1584 
1585     /**
1586      * Given an array of bytes produced by packRules, interpret them
1587      * as the start and end rules.
1588      */
1589     private void unpackRules(byte[] rules)
1590     {
1591         startDay       = rules[0];
1592         startDayOfWeek = rules[1];
1593         endDay         = rules[2];
1594         endDayOfWeek   = rules[3];
1595 
1596         // As of serial version 2, include time modes
1597         if (rules.length >= MAX_RULE_NUM) {
1598             startTimeMode = rules[4];
1599             endTimeMode   = rules[5];
1600         }
1601     }
1602 
1603     /**
1604      * Pack the start and end times into an array of bytes.  This is required
1605      * as of serial version 2.
1606      */
1607     private int[] packTimes() {
1608         int[] times = new int[2];
1609         times[0] = startTime;
1610         times[1] = endTime;
1611         return times;
1612     }
1613 
1614     /**
1615      * Unpack the start and end times from an array of bytes.  This is required
1616      * as of serial version 2.
1617      */
1618     private void unpackTimes(int[] times) {
1619         startTime = times[0];
1620         endTime = times[1];
1621     }
1622 
1623     /**
1624      * Save the state of this object to a stream (i.e., serialize it).
1625      *
1626      * @serialData We write out two formats, a JDK 1.1 compatible format, using
1627      * <code>DOW_IN_MONTH_MODE</code> rules, in the required section, followed
1628      * by the full rules, in packed format, in the optional section.  The
1629      * optional section will be ignored by JDK 1.1 code upon stream in.
1630      * <p> Contents of the optional section: The length of a byte array is
1631      * emitted (int); this is 4 as of this release. The byte array of the given
1632      * length is emitted. The contents of the byte array are the true values of
1633      * the fields <code>startDay</code>, <code>startDayOfWeek</code>,
1634      * <code>endDay</code>, and <code>endDayOfWeek</code>.  The values of these
1635      * fields in the required section are approximate values suited to the rule
1636      * mode <code>DOW_IN_MONTH_MODE</code>, which is the only mode recognized by
1637      * JDK 1.1.
1638      */
1639     private void writeObject(ObjectOutputStream stream)
1640          throws IOException
1641     {
1642         // Construct a binary rule
1643         byte[] rules = packRules();
1644         int[] times = packTimes();
1645 
1646         // Convert to 1.1 FCS rules.  This step may cause us to lose information.
1647         makeRulesCompatible();
1648 
1649         // Write out the 1.1 FCS rules
1650         stream.defaultWriteObject();
1651 
1652         // Write out the binary rules in the optional data area of the stream.
1653         stream.writeInt(rules.length);
1654         stream.write(rules);
1655         stream.writeObject(times);
1656 
1657         // Recover the original rules.  This recovers the information lost
1658         // by makeRulesCompatible.
1659         unpackRules(rules);
1660         unpackTimes(times);
1661     }
1662 
1663     /**
1664      * Reconstitute this object from a stream (i.e., deserialize it).
1665      *
1666      * We handle both JDK 1.1
1667      * binary formats and full formats with a packed byte array.
1668      */
1669     private void readObject(ObjectInputStream stream)
1670          throws IOException, ClassNotFoundException
1671     {
1672         stream.defaultReadObject();
1673 
1674         if (serialVersionOnStream < 1) {
1675             // Fix a bug in the 1.1 SimpleTimeZone code -- namely,
1676             // startDayOfWeek and endDayOfWeek were usually uninitialized.  We can't do
1677             // too much, so we assume SUNDAY, which actually works most of the time.
1678             if (startDayOfWeek == 0) {
1679                 startDayOfWeek = Calendar.SUNDAY;
1680             }
1681             if (endDayOfWeek == 0) {
1682                 endDayOfWeek = Calendar.SUNDAY;
1683             }
1684 
1685             // The variables dstSavings, startMode, and endMode are post-1.1, so they
1686             // won't be present if we're reading from a 1.1 stream.  Fix them up.
1687             startMode = endMode = DOW_IN_MONTH_MODE;
1688             dstSavings = millisPerHour;
1689         } else {
1690             // For 1.1.4, in addition to the 3 new instance variables, we also
1691             // store the actual rules (which have not be made compatible with 1.1)
1692             // in the optional area.  Read them in here and parse them.
1693             int length = stream.readInt();
1694             if (length <= MAX_RULE_NUM) {
1695                 byte[] rules = new byte[length];
1696                 stream.readFully(rules);
1697                 unpackRules(rules);
1698             } else {
1699                 throw new InvalidObjectException("Too many rules: " + length);
1700             }
1701         }
1702 
1703         if (serialVersionOnStream >= 2) {
1704             int[] times = (int[]) stream.readObject();
1705             unpackTimes(times);
1706         }
1707 
1708         serialVersionOnStream = currentSerialVersion;
1709     }
1710 }