OSDN Git Service

7d0e20198614366d35919dc81479dd2b6f1259eb
[pf3gnuchains/gcc-fork.git] / libjava / java / util / SimpleTimeZone.java
1 /* java.util.SimpleTimeZone
2    Copyright (C) 1998, 1999, 2000, 2003, 2004 Free Software Foundation, Inc.
3
4 This file is part of GNU Classpath.
5
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING.  If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
20
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library.  Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
25
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module.  An independent module is a module which is not derived from
33 or based on this library.  If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so.  If you do not wish to do so, delete this
36 exception statement from your version. */
37
38
39 package java.util;
40
41 /**
42  * This class represents a simple time zone offset and handles
43  * daylight savings.  It can only handle one daylight savings rule, so
44  * it can't represent historical changes.
45  *
46  * This object is tightly bound to the Gregorian calendar.  It assumes
47  * a regular seven days week, and the month lengths are that of the
48  * Gregorian Calendar.  It can only handle daylight savings for years
49  * lying in the AD era.
50  *
51  * @see Calendar
52  * @see GregorianCalender 
53  * @author Jochen Hoenicke
54  */
55 public class SimpleTimeZone extends TimeZone
56 {
57   /**
58    * The raw time zone offset in milliseconds to GMT, ignoring
59    * daylight savings.  
60    * @serial
61    */
62   private int rawOffset;
63
64   /**
65    * True, if this timezone uses daylight savings, false otherwise.
66    * @serial
67    */
68   private boolean useDaylight;
69
70   /**
71    * The daylight savings offset.  This is a positive offset in
72    * milliseconds with respect to standard time.  Typically this
73    * is one hour, but for some time zones this may be half an hour.
74    * @serial
75    * @since JDK1.1.4
76    */
77   private int dstSavings = 60 * 60 * 1000;
78
79   /**
80    * The first year, in which daylight savings rules applies.  
81    * @serial
82    */
83   private int startYear;
84
85   private static final int DOM_MODE = 1;
86   private static final int DOW_IN_MONTH_MODE = 2;
87   private static final int DOW_GE_DOM_MODE = 3;
88   private static final int DOW_LE_DOM_MODE = 4;
89   
90   /**
91    * The mode of the start rule. This takes one of the following values:
92    * <dl>
93    * <dt>DOM_MODE (1)</dt>
94    * <dd> startDay contains the day in month of the start date,
95    * startDayOfWeek is unused. </dd>
96    * <dt>DOW_IN_MONTH_MODE (2)</dt>
97    * <dd> The startDay gives the day of week in month, and
98    * startDayOfWeek the day of week.  For example startDay=2 and
99    * startDayOfWeek=Calender.SUNDAY specifies that the change is on
100    * the second sunday in that month.  You must make sure, that this
101    * day always exists (ie. don't specify the 5th sunday).
102    * </dd>
103    * <dt>DOW_GE_DOM_MODE (3)</dt>
104    * <dd> The start is on the first startDayOfWeek on or after
105    * startDay.  For example startDay=13 and
106    * startDayOfWeek=Calendar.FRIDAY specifies that the daylight
107    * savings start on the first FRIDAY on or after the 13th of that
108    * Month. Make sure that the change is always in the given month, or
109    * the result is undefined.
110    * </dd>
111    * <dt>DOW_LE_DOM_MONTH (4)</dt>
112    * <dd> The start is on the first startDayOfWeek on or before the
113    * startDay.  Make sure that the change is always in the given
114    * month, or the result is undefined.
115    </dd>
116    * </dl>
117    * @serial */
118   private int startMode;
119
120   /**
121    * The month in which daylight savings start.  This is one of the
122    * constants Calendar.JANUARY, ..., Calendar.DECEMBER.  
123    * @serial
124    */
125   private int startMonth;
126
127   /**
128    * This variable can have different meanings.  See startMode for details
129    * @see #startMode;
130    * @serial
131    */   
132   private int startDay;
133   
134   /**
135    * This variable specifies the day of week the change takes place.  If 
136    * startMode == DOM_MODE, this is undefined.
137    * @serial
138    * @see #startMode;
139    */   
140   private int startDayOfWeek;
141   
142   /**
143    * This variable specifies the time of change to daylight savings.
144    * This time is given in milliseconds after midnight local
145    * standard time.  
146    * @serial
147    */
148   private int startTime;
149
150   /**
151    * This variable specifies the mode that startTime is specified in.  By
152    * default it is WALL_TIME, but can also be STANDARD_TIME or UTC_TIME.  For
153    * startTime, STANDARD_TIME and WALL_TIME are equivalent.
154    * @serial
155    */
156   private int startTimeMode = WALL_TIME;
157
158   /**
159    * The month in which daylight savings ends.  This is one of the
160    * constants Calendar.JANUARY, ..., Calendar.DECEMBER.  
161    * @serial
162    */   
163   private int endMonth;
164
165   /**
166    * This variable gives the mode for the end of daylight savings rule.
167    * It can take the same values as startMode.
168    * @serial
169    * @see #startMode
170    */   
171   private int endMode;
172
173   /**
174    * This variable can have different meanings.  See startMode for details
175    * @serial
176    * @see #startMode;
177    */
178   private int endDay;
179   
180   /**
181    * This variable specifies the day of week the change takes place.  If 
182    * endMode == DOM_MODE, this is undefined.
183    * @serial
184    * @see #startMode;
185    */
186   private int endDayOfWeek;
187   
188   /**
189    * This variable specifies the time of change back to standard time.
190    * This time is given in milliseconds after midnight local
191    * standard time.  
192    * @serial
193    */
194   private int endTime;
195
196   /**
197    * This variable specifies the mode that endTime is specified in.  By
198    * default it is WALL_TIME, but can also be STANDARD_TIME or UTC_TIME.
199    * @serial
200    */
201   private int endTimeMode = WALL_TIME;
202
203   /**
204    * This variable points to a deprecated array from JDK 1.1.  It is
205    * ignored in JDK 1.2 but streamed out for compatibility with JDK 1.1.
206    * The array contains the lengths of the months in the year and is
207    * assigned from a private static final field to avoid allocating
208    * the array for every instance of the object.
209    * Note that static final fields are not serialized.
210    * @serial
211    */
212   private byte[] monthLength = monthArr;
213   private static final byte[] monthArr =
214     {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
215
216   /**
217    * The version of the serialized data on the stream.
218    * <dl>
219    * <dt>0 or not present on stream</dt>
220    * <dd> JDK 1.1.3 or earlier, only provides this fields:
221    * rawOffset, startDay, startDayOfWeek, startMonth, startTime,
222    * startYear, endDay, endDayOfWeek, endMonth, endTime
223    * </dd>
224    * <dd> JDK 1.1.4 or later. This includes three new fields, namely
225    * startMode, endMode and dstSavings.  And there is a optional section
226    * as described in writeObject.
227    * </dd>
228    *
229    * XXX - JDK 1.2 Beta 4 docu states 1.1.4, but my 1.1.5 has the old
230    * version.
231    *
232    * When streaming out this class it is always written in the latest
233    * version.
234    * @serial
235    * @since JDK1.1.4 
236    */
237   private int serialVersionOnStream = 2;
238
239   private static final long serialVersionUID = -403250971215465050L;
240
241   /**
242    * Constant to indicate that start and end times are specified in standard
243    * time, without adjusting for daylight savings.
244    */
245   public static final int STANDARD_TIME = 1;
246
247   /**
248    * Constant to indicate that start and end times are specified in wall
249    * time, adjusting for daylight savings.  This is the default.
250    */
251   public static final int WALL_TIME = 0;
252
253   /**
254    * Constant to indicate that start and end times are specified in UTC.
255    */
256   public static final int UTC_TIME = 2;
257
258   /**
259    * Create a <code>SimpleTimeZone</code> with the given time offset
260    * from GMT and without daylight savings.  
261    * @param rawOffset the time offset from GMT in milliseconds.
262    * @param id The identifier of this time zone.  
263    */
264   public SimpleTimeZone(int rawOffset, String id)
265   {
266     this.rawOffset = rawOffset;
267     setID(id);
268     useDaylight = false;
269     startYear = 0;
270   }
271
272   /**
273    * Create a <code>SimpleTimeZone</code> with the given time offset
274    * from GMT and with daylight savings.  The start/end parameters
275    * can have different meaning (replace WEEKDAY with a real day of
276    * week). Only the first two meanings were supported by earlier 
277    * versions of jdk.
278    *
279    * <dl>
280    * <dt><code>day &gt; 0, dayOfWeek = Calendar.WEEKDAY</code></dt>
281    * <dd>The start/end of daylight savings is on the <code>day</code>-th
282    * <code>WEEKDAY</code> in the given month. </dd>
283    * <dt><code>day &lt; 0, dayOfWeek = Calendar.WEEKDAY</code></dt>
284    * <dd>The start/end of daylight savings is on the <code>-day</code>-th
285    * <code>WEEKDAY</code> counted from the <i>end</i> of the month. </dd>
286    * <dt><code>day &gt; 0, dayOfWeek = 0</code></dt>
287    * <dd>The start/end of daylight is on the <code>day</code>-th day of
288    * the month. </dd>
289    * <dt><code>day &gt; 0, dayOfWeek = -Calendar.WEEKDAY</code></dt>
290    * <dd>The start/end of daylight is on the first WEEKDAY on or after
291    * the <code>day</code>-th day of the month.  You must make sure that
292    * this day lies in the same month. </dd>
293    * <dt><code>day &lt; 0, dayOfWeek = -Calendar.WEEKDAY</code></dt>
294    * <dd>The start/end of daylight is on the first WEEKDAY on or
295    * <i>before</i> the <code>-day</code>-th day of the month.  You
296    * must make sure that this day lies in the same month. </dd>
297    * </dl>
298    *
299    * If you give a non existing month, a day that is zero, or too big, 
300    * or a dayOfWeek that is too big,  the result is undefined.
301    *
302    * The start rule must have a different month than the end rule.
303    * This restriction shouldn't hurt for all possible time zones.
304    * 
305    * @param rawOffset The time offset from GMT in milliseconds.
306    * @param id  The identifier of this time zone.
307    * @param startMonth The start month of daylight savings; use the
308    * constants in Calendar.
309    * @param startday A day in month or a day of week number, as
310    * described above.
311    * @param startDayOfWeek The start rule day of week; see above.
312    * @param startTime A time in millis in standard time.
313    * @param endMonth The end month of daylight savings; use the
314    * constants in Calendar.
315    * @param endday A day in month or a day of week number, as 
316    * described above.
317    * @param endDayOfWeek The end rule day of week; see above.
318    * @param endTime A time in millis in standard time.
319    * @throws IllegalArgumentException if parameters are invalid or out of
320    * range.
321    */
322   public SimpleTimeZone(int rawOffset, String id,
323                         int startMonth, int startDayOfWeekInMonth,
324                         int startDayOfWeek, int startTime,
325                         int endMonth, int endDayOfWeekInMonth,
326                         int endDayOfWeek, int endTime)
327   {
328     this.rawOffset = rawOffset;
329     setID(id);
330     useDaylight = true;
331
332     setStartRule(startMonth, startDayOfWeekInMonth,
333                  startDayOfWeek, startTime);
334     setEndRule(endMonth, endDayOfWeekInMonth, endDayOfWeek, endTime);
335     if (startMonth == endMonth)
336       throw new IllegalArgumentException
337         ("startMonth and endMonth must be different");
338     this.startYear = 0;
339   }
340
341   /**
342    * This constructs a new SimpleTimeZone that supports a daylight savings
343    * rule.  The parameter are the same as for the constructor above, except
344    * there is the additional dstSavaings parameter.
345    *
346    * @param dstSavings the amount of savings for daylight savings
347    * time in milliseconds.  This must be positive.
348    * @since 1.2
349    */
350   public SimpleTimeZone(int rawOffset, String id,
351                         int startMonth, int startDayOfWeekInMonth,
352                         int startDayOfWeek, int startTime,
353                         int endMonth, int endDayOfWeekInMonth,
354                         int endDayOfWeek, int endTime, int dstSavings)
355   {
356     this(rawOffset, id,
357          startMonth, startDayOfWeekInMonth, startDayOfWeek, startTime,
358          endMonth, endDayOfWeekInMonth, endDayOfWeek, endTime);
359
360     this.dstSavings = dstSavings;
361   }
362
363   /**
364    * This constructs a new SimpleTimeZone that supports a daylight savings
365    * rule.  The parameter are the same as for the constructor above, except
366    * there are the additional startTimeMode, endTimeMode, and dstSavings
367    * parameters.
368    *
369    * @param startTimeMode the mode that start times are specified in.  One of
370    * WALL_TIME, STANDARD_TIME, or UTC_TIME.
371    * @param endTimeMode the mode that end times are specified in.  One of
372    * WALL_TIME, STANDARD_TIME, or UTC_TIME.
373    * @param dstSavings the amount of savings for daylight savings
374    * time in milliseconds.  This must be positive.
375    * @throws IllegalArgumentException if parameters are invalid or out of
376    * range.
377    * @since 1.4
378    */
379   public SimpleTimeZone(int rawOffset, String id,
380                         int startMonth, int startDayOfWeekInMonth,
381                         int startDayOfWeek, int startTime, int startTimeMode,
382                         int endMonth, int endDayOfWeekInMonth,
383                         int endDayOfWeek, int endTime, int endTimeMode,
384                         int dstSavings)
385   {
386     this.rawOffset = rawOffset;
387     setID(id);
388     useDaylight = true;
389
390     if (startTimeMode < WALL_TIME || startTimeMode > UTC_TIME)
391       throw new IllegalArgumentException("startTimeMode must be one of WALL_TIME, STANDARD_TIME, or UTC_TIME");
392     if (endTimeMode < WALL_TIME || endTimeMode > UTC_TIME)
393       throw new IllegalArgumentException("endTimeMode must be one of WALL_TIME, STANDARD_TIME, or UTC_TIME");
394     this.startTimeMode = startTimeMode;
395     this.endTimeMode = endTimeMode;
396
397     setStartRule(startMonth, startDayOfWeekInMonth,
398                  startDayOfWeek, startTime);
399     setEndRule(endMonth, endDayOfWeekInMonth, endDayOfWeek, endTime);
400     if (startMonth == endMonth)
401       throw new IllegalArgumentException
402         ("startMonth and endMonth must be different");
403     this.startYear = 0;
404
405     this.dstSavings = dstSavings;
406   }
407
408   /**
409    * Sets the first year, where daylight savings applies.  The daylight
410    * savings rule never apply for years in the BC era.  Note that this
411    * is gregorian calendar specific.
412    * @param year the start year.
413    */
414   public void setStartYear(int year)
415   {
416     startYear = year;
417     useDaylight = true;
418   }
419
420   /**
421    * Checks if the month, day, dayOfWeek arguments are in range and
422    * returns the mode of the rule.
423    * @param month the month parameter as in the constructor
424    * @param day the day parameter as in the constructor
425    * @param dayOfWeek the day of week parameter as in the constructor
426    * @return the mode of this rule see startMode.
427    * @exception IllegalArgumentException if parameters are out of range.
428    * @see #SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)
429    * @see #startMode
430    */
431   private int checkRule(int month, int day, int dayOfWeek)
432   {
433     if (month < 0 || month > 11)
434       throw new IllegalArgumentException("month out of range");
435     int daysInMonth = getDaysInMonth(month, 1);
436     if (dayOfWeek == 0)
437       {
438         if (day <= 0 || day > daysInMonth)
439           throw new IllegalArgumentException("day out of range");
440         return DOM_MODE;
441       }
442     else if (dayOfWeek > 0)
443       {
444         if (Math.abs(day) > (daysInMonth + 6) / 7)
445           throw new IllegalArgumentException("dayOfWeekInMonth out of range");
446         if (dayOfWeek > Calendar.SATURDAY)
447           throw new IllegalArgumentException("dayOfWeek out of range");
448         return DOW_IN_MONTH_MODE;
449       }
450     else
451       {
452         if (day == 0 || Math.abs(day) > daysInMonth)
453           throw new IllegalArgumentException("day out of range");
454         if (dayOfWeek < -Calendar.SATURDAY)
455           throw new IllegalArgumentException("dayOfWeek out of range");
456         if (day < 0)
457           return DOW_LE_DOM_MODE;
458         else
459           return DOW_GE_DOM_MODE;
460       }
461   }
462
463
464   /**
465    * Sets the daylight savings start rule.  You must also set the
466    * end rule with <code>setEndRule</code> or the result of
467    * getOffset is undefined.  For the parameters see the ten-argument
468    * constructor above.
469    *
470    * @param month The month where daylight savings start, zero
471    * based.  You should use the constants in Calendar.
472    * @param day A day of month or day of week in month.
473    * @param dayOfWeek The day of week where daylight savings start.
474    * @param time The time in milliseconds standard time where daylight
475    * savings start.
476    * @see SimpleTimeZone
477    */
478   public void setStartRule(int month, int day, int dayOfWeek, int time)
479   {
480     this.startMode = checkRule(month, day, dayOfWeek);
481     this.startMonth = month;
482     this.startDay = day;
483     this.startDayOfWeek = Math.abs(dayOfWeek);
484     if (this.startTimeMode == WALL_TIME || this.startTimeMode == STANDARD_TIME)
485       this.startTime = time;
486     else
487       // Convert from UTC to STANDARD
488       this.startTime = time + this.rawOffset;
489     useDaylight = true;
490   }
491
492   /**
493    * Sets the daylight savings start rule.  You must also set the
494    * end rule with <code>setEndRule</code> or the result of
495    * getOffset is undefined.  For the parameters see the ten-argument
496    * constructor above.
497    *
498    * Note that this API isn't incredibly well specified.  It appears that the
499    * after flag must override the parameters, since normally, the day and
500    * dayofweek can select this.  I.e., if day < 0 and dayOfWeek < 0, on or
501    * before mode is chosen.  But if after == true, this implementation
502    * overrides the signs of the other arguments.  And if dayOfWeek == 0, it
503    * falls back to the behavior in the other APIs.  I guess this should be
504    * checked against Sun's implementation.
505    *
506    * @param month The month where daylight savings start, zero
507    * based.  You should use the constants in Calendar.
508    * @param day A day of month or day of week in month.
509    * @param dayOfWeek The day of week where daylight savings start.
510    * @param time The time in milliseconds standard time where daylight
511    * savings start.
512    * @param after If true, day and dayOfWeek specify first day of week on or
513    * after day, else first day of week on or before.
514    * @since 1.2
515    * @see SimpleTimeZone
516    */
517   public void setStartRule(int month, int day, int dayOfWeek, int time, boolean after)
518   {
519     // FIXME: XXX: Validate that checkRule and offset processing work with on
520     // or before mode.
521     this.startDay = after ? Math.abs(day) : -Math.abs(day);
522     this.startDayOfWeek = after ? Math.abs(dayOfWeek) : -Math.abs(dayOfWeek);
523     this.startMode = (dayOfWeek != 0) ? (after ? DOW_GE_DOM_MODE : DOW_LE_DOM_MODE)
524       : checkRule(month, day, dayOfWeek);
525     this.startDay = Math.abs(this.startDay);
526     this.startDayOfWeek = Math.abs(this.startDayOfWeek);
527
528     this.startMonth = month;
529
530     if (this.startTimeMode == WALL_TIME || this.startTimeMode == STANDARD_TIME)
531       this.startTime = time;
532     else
533       // Convert from UTC to STANDARD
534       this.startTime = time + this.rawOffset;
535     useDaylight = true;
536   }
537
538   /**
539    * Sets the daylight savings start rule.  You must also set the
540    * end rule with <code>setEndRule</code> or the result of
541    * getOffset is undefined.  For the parameters see the ten-argument
542    * constructor above.
543    *
544    * @param month The month where daylight savings start, zero
545    * based.  You should use the constants in Calendar.
546    * @param day A day of month or day of week in month.
547    * @param time The time in milliseconds standard time where daylight
548    * savings start.
549    * @see SimpleTimeZone
550    * @since 1.2
551    */
552   public void setStartRule(int month, int day, int time)
553   {
554     setStartRule(month, day, 0, time);
555   }
556
557   /**
558    * Sets the daylight savings end rule.  You must also set the
559    * start rule with <code>setStartRule</code> or the result of
560    * getOffset is undefined. For the parameters see the ten-argument
561    * constructor above.
562    *
563    * @param month The end month of daylight savings.
564    * @param day A day in month, or a day of week in month.
565    * @param dayOfWeek A day of week, when daylight savings ends.
566    * @param time A time in millis in standard time.
567    * @see #setStartRule
568    */
569   public void setEndRule(int month, int day, int dayOfWeek, int time)
570   {
571     this.endMode = checkRule(month, day, dayOfWeek);
572     this.endMonth = month;
573     this.endDay = day;
574     this.endDayOfWeek = Math.abs(dayOfWeek);
575     if (this.endTimeMode == WALL_TIME)
576       this.endTime = time;
577     else if (this.endTimeMode == STANDARD_TIME)
578       // Convert from STANDARD to DST
579       this.endTime = time + this.dstSavings;
580     else
581       // Convert from UTC to DST
582       this.endTime = time + this.rawOffset + this.dstSavings;
583     useDaylight = true;
584   }
585
586   /**
587    * Sets the daylight savings end rule.  You must also set the
588    * start rule with <code>setStartRule</code> or the result of
589    * getOffset is undefined. For the parameters see the ten-argument
590    * constructor above.
591    *
592    * Note that this API isn't incredibly well specified.  It appears that the
593    * after flag must override the parameters, since normally, the day and
594    * dayofweek can select this.  I.e., if day &lt; 0 and dayOfWeek &lt; 0, on or
595    * before mode is chosen.  But if after == true, this implementation
596    * overrides the signs of the other arguments.  And if dayOfWeek == 0, it
597    * falls back to the behavior in the other APIs.  I guess this should be
598    * checked against Sun's implementation.
599    *
600    * @param month The end month of daylight savings.
601    * @param day A day in month, or a day of week in month.
602    * @param dayOfWeek A day of week, when daylight savings ends.
603    * @param time A time in millis in standard time.
604    * @param after If true, day and dayOfWeek specify first day of week on or
605    * after day, else first day of week on or before.
606    * @since 1.2
607    * @see #setStartRule
608    */
609   public void setEndRule(int month, int day, int dayOfWeek, int time, boolean after)
610   {
611     // FIXME: XXX: Validate that checkRule and offset processing work with on
612     // or before mode.
613     this.endDay = after ? Math.abs(day) : -Math.abs(day);
614     this.endDayOfWeek = after ? Math.abs(dayOfWeek) : -Math.abs(dayOfWeek);
615     this.endMode = (dayOfWeek != 0) ? (after ? DOW_GE_DOM_MODE : DOW_LE_DOM_MODE)
616       : checkRule(month, day, dayOfWeek);
617     this.endDay = Math.abs(this.endDay);
618     this.endDayOfWeek = Math.abs(endDayOfWeek);
619
620     this.endMonth = month;
621
622     if (this.endTimeMode == WALL_TIME)
623       this.endTime = time;
624     else if (this.endTimeMode == STANDARD_TIME)
625       // Convert from STANDARD to DST
626       this.endTime = time + this.dstSavings;
627     else
628       // Convert from UTC to DST
629       this.endTime = time + this.rawOffset + this.dstSavings;
630     useDaylight = true;
631   }
632
633   /**
634    * Sets the daylight savings end rule.  You must also set the
635    * start rule with <code>setStartRule</code> or the result of
636    * getOffset is undefined. For the parameters see the ten-argument
637    * constructor above.
638    *
639    * @param month The end month of daylight savings.
640    * @param day A day in month, or a day of week in month.
641    * @param dayOfWeek A day of week, when daylight savings ends.
642    * @param time A time in millis in standard time.
643    * @see #setStartRule
644    */
645   public void setEndRule(int month, int day, int time)
646   {
647     setEndRule(month, day, 0, time);
648   }
649
650   /**
651    * Gets the time zone offset, for current date, modified in case of 
652    * daylight savings.  This is the offset to add to UTC to get the local
653    * time.
654    *
655    * In the standard JDK the results given by this method may result in
656    * inaccurate results at the end of February or the beginning of March.
657    * To avoid this, you should use Calendar instead:
658    * <code>offset = cal.get(Calendar.ZONE_OFFSET)
659    * + cal.get(Calendar.DST_OFFSET);</code>
660    *
661    * This version doesn't suffer this inaccuracy.
662    *
663    * The arguments don't follow the approach for setting start and end rules.
664    * The day must be a positive number and dayOfWeek must be a positive value
665    * from Calendar.  dayOfWeek is redundant, but must match the other values
666    * or an inaccurate result may be returned.
667    *
668    * @param era the era of the given date
669    * @param year the year of the given date
670    * @param month the month of the given date, 0 for January.
671    * @param day the day of month
672    * @param dayOfWeek the day of week; this must match the other fields.
673    * @param millis the millis in the day (in local standard time)
674    * @return the time zone offset in milliseconds.
675    * @throws IllegalArgumentException if arguments are incorrect.
676    */
677   public int getOffset(int era, int year, int month,
678                        int day, int dayOfWeek, int millis)
679   {
680     int daysInMonth = getDaysInMonth(month, year);
681     if (day < 1 || day > daysInMonth)
682       throw new IllegalArgumentException("day out of range");
683     if (dayOfWeek < Calendar.SUNDAY || dayOfWeek > Calendar.SATURDAY)
684       throw new IllegalArgumentException("dayOfWeek out of range");
685     if (month < Calendar.JANUARY || month > Calendar.DECEMBER)
686       throw new IllegalArgumentException("month out of range");
687
688     // This method is called by Calendar, so we mustn't use that class.
689     int daylightSavings = 0;
690     if (useDaylight && era == GregorianCalendar.AD && year >= startYear)
691       {
692         // This does only work for Gregorian calendars :-(
693         // This is mainly because setStartYear doesn't take an era.
694
695         boolean afterStart = !isBefore(year, month, day, dayOfWeek, millis,
696                                        startMode, startMonth,
697                                        startDay, startDayOfWeek, startTime);
698         boolean beforeEnd = isBefore(year, month, day, dayOfWeek,
699                                      millis + dstSavings,
700                                      endMode, endMonth,
701                                      endDay, endDayOfWeek, endTime);
702
703         if (startMonth < endMonth)
704           {
705             // use daylight savings, if the date is after the start of
706             // savings, and before the end of savings.
707             daylightSavings = afterStart && beforeEnd ? dstSavings : 0;
708           }
709         else
710           {
711             // use daylight savings, if the date is before the end of
712             // savings, or after the start of savings.
713             daylightSavings = beforeEnd || afterStart ? dstSavings : 0;
714           }
715       }
716     return rawOffset + daylightSavings;
717   }
718
719   /**
720    * Returns the time zone offset to GMT in milliseconds, ignoring
721    * day light savings.
722    * @return the time zone offset.
723    */
724   public int getRawOffset()
725   {
726     return rawOffset;
727   }
728
729   /**
730    * Sets the standard time zone offset to GMT.
731    * @param rawOffset The time offset from GMT in milliseconds.
732    */
733   public void setRawOffset(int rawOffset)
734   {
735     this.rawOffset = rawOffset;
736   }
737
738   /**
739    * Gets the daylight savings offset.  This is a positive offset in
740    * milliseconds with respect to standard time.  Typically this
741    * is one hour, but for some time zones this may be half an our.
742    * @return the daylight savings offset in milliseconds.
743    * 
744    * @since 1.2
745    */
746   public int getDSTSavings()
747   {
748     return dstSavings;
749   }
750
751   /**
752    * Sets the daylight savings offset.  This is a positive offset in
753    * milliseconds with respect to standard time.
754    *
755    * @param dstSavings the daylight savings offset in milliseconds.
756    *
757    * @since 1.2
758    */
759   public void setDSTSavings(int dstSavings)
760   {
761     if (dstSavings <= 0)
762       throw new IllegalArgumentException("illegal value for dstSavings");
763     
764     this.dstSavings = dstSavings;
765   }
766
767   /**
768    * Returns if this time zone uses daylight savings time.
769    * @return true, if we use daylight savings time, false otherwise.
770    */
771   public boolean useDaylightTime()
772   {
773     return useDaylight;
774   }
775
776   /**
777    * Returns the number of days in the given month.  It does always
778    * use the Gregorian leap year rule.  
779    * @param month The month, zero based; use one of the Calendar constants.
780    * @param year  The year.
781    */
782   private int getDaysInMonth(int month, int year)
783   {
784     // Most of this is copied from GregorianCalendar.getActualMaximum()
785     if (month == Calendar.FEBRUARY)
786       {
787         return ((year & 3) == 0 && (year % 100 != 0 || year % 400 == 0))
788           ? 29 : 28;
789       }
790     else if (month < Calendar.AUGUST)
791         return 31 - (month & 1);
792     else
793       return 30 + (month & 1);
794   }
795
796   /**
797    * Checks if the date given in calXXXX, is before the change between
798    * dst and standard time.
799    * @param calYear the year of the date to check (for leap day checking).
800    * @param calMonth the month of the date to check.
801    * @param calDay the day of month of the date to check.
802    * @param calDayOfWeek the day of week of the date to check.
803    * @param calMillis the millis of day of the date to check (standard time).
804    * @param mode  the change mode; same semantic as startMode.
805    * @param month the change month; same semantic as startMonth.
806    * @param day   the change day; same semantic as startDay.
807    * @param dayOfWeek the change day of week; 
808    * @param millis the change time in millis since midnight standard time.
809    * same semantic as startDayOfWeek.
810    * @return true, if cal is before the change, false if cal is on
811    * or after the change.
812    */
813   private boolean isBefore(int calYear,
814                            int calMonth, int calDayOfMonth, int calDayOfWeek,
815                            int calMillis, int mode, int month,
816                            int day, int dayOfWeek, int millis)
817   {
818
819     // This method is called by Calendar, so we mustn't use that class.
820     // We have to do all calculations by hand.
821
822     // check the months:
823
824     // XXX - this is not correct:
825     // for the DOW_GE_DOM and DOW_LE_DOM modes the change date may
826     // be in a different month.
827     if (calMonth != month)
828       return calMonth < month;
829
830     // check the day:
831     switch (mode)
832       {
833       case DOM_MODE:
834         if (calDayOfMonth != day)
835           return calDayOfMonth < day;
836         break;
837       case DOW_IN_MONTH_MODE:
838         {
839           // This computes the day of month of the day of type
840           // "dayOfWeek" that lies in the same (sunday based) week as cal.
841           calDayOfMonth += (dayOfWeek - calDayOfWeek);
842
843           // Now we convert it to 7 based number (to get a one based offset
844           // after dividing by 7).  If we count from the end of the
845           // month, we get want a -7 based number counting the days from 
846           // the end:
847
848           if (day < 0)
849             calDayOfMonth -= getDaysInMonth(calMonth, calYear) + 7;
850           else
851             calDayOfMonth += 6;
852
853           //  day > 0                    day < 0
854           //  S  M  T  W  T  F  S        S  M  T  W  T  F  S
855           //     7  8  9 10 11 12         -36-35-34-33-32-31
856           // 13 14 15 16 17 18 19      -30-29-28-27-26-25-24
857           // 20 21 22 23 24 25 26      -23-22-21-20-19-18-17
858           // 27 28 29 30 31 32 33      -16-15-14-13-12-11-10
859           // 34 35 36                   -9 -8 -7
860
861           // Now we calculate the day of week in month:
862           int week = calDayOfMonth / 7;
863           //  day > 0                    day < 0
864           //  S  M  T  W  T  F  S        S  M  T  W  T  F  S
865           //     1  1  1  1  1  1          -5 -5 -4 -4 -4 -4
866           //  1  2  2  2  2  2  2       -4 -4 -4 -3 -3 -3 -3
867           //  2  3  3  3  3  3  3       -3 -3 -3 -2 -2 -2 -2
868           //  3  4  4  4  4  4  4       -2 -2 -2 -1 -1 -1 -1
869           //  4  5  5                   -1 -1 -1
870
871           if (week != day)
872             return week < day;
873
874           if (calDayOfWeek != dayOfWeek)
875             return calDayOfWeek < dayOfWeek;
876
877           // daylight savings starts/ends  on the given day.
878           break;
879         }
880
881       case DOW_LE_DOM_MODE:
882         // The greatest sunday before or equal December, 12
883         // is the same as smallest sunday after or equal December, 6.
884         day = Math.abs(day) - 6;
885
886       case DOW_GE_DOM_MODE:
887
888         // Calculate the day of month of the day of type
889         // "dayOfWeek" that lies before (or on) the given date.
890         calDayOfMonth -= (calDayOfWeek < dayOfWeek ? 7 : 0)
891           + calDayOfWeek - dayOfWeek;
892         if (calDayOfMonth < day)
893           return true;
894         if (calDayOfWeek != dayOfWeek || calDayOfMonth >= day + 7)
895           return false;
896         // now we have the same day
897         break;
898       }
899     // the millis decides:
900     return (calMillis < millis);
901   }
902
903   /**
904    * Determines if the given date is in daylight savings time.
905    * @return true, if it is in daylight savings time, false otherwise.
906    */
907   public boolean inDaylightTime(Date date)
908   {
909     Calendar cal = Calendar.getInstance(this);
910     cal.setTime(date);
911     return (cal.get(Calendar.DST_OFFSET) != 0);
912   }
913
914   /**
915    * Generates the hashCode for the SimpleDateFormat object.  It is
916    * the rawOffset, possibly, if useDaylightSavings is true, xored
917    * with startYear, startMonth, startDayOfWeekInMonth, ..., endTime.  
918    */
919   public synchronized int hashCode()
920   {
921     return rawOffset ^
922       (useDaylight ?
923        startMonth ^ startDay ^ startDayOfWeek ^ startTime
924        ^ endMonth ^ endDay ^ endDayOfWeek ^ endTime : 0);
925   }
926
927   public synchronized boolean equals(Object o)
928   {
929     if (this == o)
930       return true;
931     if (!(o instanceof SimpleTimeZone))
932       return false;
933     SimpleTimeZone zone = (SimpleTimeZone) o;
934     if (zone.hashCode() != hashCode()
935         || !getID().equals(zone.getID())
936         || rawOffset != zone.rawOffset || useDaylight != zone.useDaylight)
937       return false;
938     if (!useDaylight)
939       return true;
940     return (startYear == zone.startYear
941             && startMonth == zone.startMonth
942             && startDay == zone.startDay
943             && startDayOfWeek == zone.startDayOfWeek
944             && startTime == zone.startTime
945             && startTimeMode == zone.startTimeMode
946             && endMonth == zone.endMonth
947             && endDay == zone.endDay
948             && endDayOfWeek == zone.endDayOfWeek
949             && endTime == zone.endTime
950             && endTimeMode == zone.endTimeMode);
951   }
952
953   /**
954    * Test if the other time zone uses the same rule and only
955    * possibly differs in ID.  This implementation for this particular
956    * class will return true if the other object is a SimpleTimeZone,
957    * the raw offsets and useDaylight are identical and if useDaylight
958    * is true, also the start and end datas are identical.
959    * @return true if this zone uses the same rule.
960    */
961   public boolean hasSameRules(TimeZone other)
962   {
963     if (this == other)
964       return true;
965     if (!(other instanceof SimpleTimeZone))
966       return false;
967     SimpleTimeZone zone = (SimpleTimeZone) other;
968     if (zone.hashCode() != hashCode()
969         || rawOffset != zone.rawOffset || useDaylight != zone.useDaylight)
970       return false;
971     if (!useDaylight)
972       return true;
973     return (startYear == zone.startYear
974             && startMonth == zone.startMonth
975             && startDay == zone.startDay
976             && startDayOfWeek == zone.startDayOfWeek
977             && startTime == zone.startTime
978             && startTimeMode == zone.startTimeMode
979             && endMonth == zone.endMonth
980             && endDay == zone.endDay
981             && endDayOfWeek == zone.endDayOfWeek
982             && endTime == zone.endTime
983             && endTimeMode == zone.endTimeMode);
984   }
985
986   /**
987    * Returns a string representation of this SimpleTimeZone object.
988    * @return a string representation of this SimpleTimeZone object.
989    */
990   public String toString()
991   {
992     // the test for useDaylight is an incompatibility to jdk1.2, but
993     // I think this shouldn't hurt.
994     return getClass().getName() + "["
995       + "id=" + getID()
996       + ",offset=" + rawOffset
997       + ",dstSavings=" + dstSavings
998       + ",useDaylight=" + useDaylight
999       + (useDaylight ?
1000          ",startYear=" + startYear
1001          + ",startMode=" + startMode
1002          + ",startMonth=" + startMonth
1003          + ",startDay=" + startDay
1004          + ",startDayOfWeek=" + startDayOfWeek
1005          + ",startTime=" + startTime
1006          + ",startTimeMode=" + startTimeMode
1007          + ",endMode=" + endMode
1008          + ",endMonth=" + endMonth
1009          + ",endDay=" + endDay
1010          + ",endDayOfWeek=" + endDayOfWeek
1011          + ",endTime=" + endTime
1012          + ",endTimeMode=" + endTimeMode
1013          : "") + "]";
1014   }
1015
1016   /**
1017    * Reads a serialized simple time zone from stream.
1018    * @see #writeObject
1019    */
1020   private void readObject(java.io.ObjectInputStream input)
1021     throws java.io.IOException, ClassNotFoundException
1022   {
1023     input.defaultReadObject();
1024     if (serialVersionOnStream == 0)
1025       {
1026         // initialize the new fields to default values.
1027         dstSavings = 60 * 60 * 1000;
1028         endMode = DOW_IN_MONTH_MODE;
1029         startMode = DOW_IN_MONTH_MODE;
1030         startTimeMode = WALL_TIME;
1031         endTimeMode = WALL_TIME;
1032         serialVersionOnStream = 2;      }
1033     else
1034       {
1035         int length = input.readInt();
1036         byte[] byteArray = new byte[length];
1037         input.read(byteArray, 0, length);
1038         if (length >= 4)
1039           {
1040             // Lets hope that Sun does extensions to the serialized
1041             // form in a sane manner.
1042             startDay = byteArray[0];
1043             startDayOfWeek = byteArray[1];
1044             endDay = byteArray[2];
1045             endDayOfWeek = byteArray[3];
1046           }
1047       }
1048   }
1049
1050   /**
1051    * Serializes this object to a stream.  @serialdata The object is
1052    * first written in the old JDK 1.1 format, so that it can be read
1053    * by by the old classes.  This means, that the
1054    * <code>start/endDay(OfWeek)</code>-Fields are written in the
1055    * DOW_IN_MONTH_MODE rule, since this was the only supported rule
1056    * in 1.1.
1057    * 
1058    * In the optional section, we write first the length of an byte
1059    * array as int and afterwards the byte array itself.  The byte
1060    * array contains in this release four elements, namely the real
1061    * startDay, startDayOfWeek endDay, endDayOfWeek in that Order.
1062    * These fields are needed, because for compatibility reasons only
1063    * approximative values are written to the required section, as
1064    * described above.  
1065    */
1066   private void writeObject(java.io.ObjectOutputStream output)
1067     throws java.io.IOException
1068   {
1069     byte[] byteArray = new byte[]
1070     {
1071       (byte) startDay, (byte) startDayOfWeek,
1072         (byte) endDay, (byte) endDayOfWeek};
1073
1074     /* calculate the approximation for JDK 1.1 */
1075     switch (startMode)
1076       {
1077       case DOM_MODE:
1078         startDayOfWeek = Calendar.SUNDAY;       // random day of week
1079         // fall through
1080       case DOW_GE_DOM_MODE:
1081       case DOW_LE_DOM_MODE:
1082         startDay = (startDay + 6) / 7;
1083       }
1084     switch (endMode)
1085       {
1086       case DOM_MODE:
1087         endDayOfWeek = Calendar.SUNDAY;
1088         // fall through
1089       case DOW_GE_DOM_MODE:
1090       case DOW_LE_DOM_MODE:
1091         endDay = (endDay + 6) / 7;
1092       }
1093
1094     // the required part:
1095     output.defaultWriteObject();
1096     // the optional part:
1097     output.writeInt(byteArray.length);
1098     output.write(byteArray, 0, byteArray.length);
1099   }
1100 }