Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I am learning GoF Java Design Patterns and I want to see some real life examples of them. Can you guys point to some good usage of these Design Patterns.(preferably in Java's core libraries). Thank you
Could someone please advise the current "best practice" around Date and Calendar types. When writing new code, is it best to always favour Calendar over Date, or are there circumstances where Date is the more appropriate datatype?
I'm looking for standards for Date/Time addition. I haven't been able to find any. In particular I'm hoping to find a spec that defines what should happen when you add a month to a date like January 31st. Is the right answer February 28th(/29th)? March 1st? March 2nd? I've seen inconsistent implementations between different tools (PHP & MySQL in this case), and I'm trying to find some sort...
I just noticed that java.util.Observable is a concrete class. Since the purpose of Observable is to be extended, this seems rather odd to me. Is there a reason why it was implemented this way? I found this article which says that The observable is a concrete class, so the class deriving from it must be determined upfront, as Java allows only single inheritance. But that doesn't really e...
I am getting date in the format as yyyy-mm-dd. I need to increment this by one day. How can I do this?
Does anyone know a good date parser for different languages/locales. The built-in parser of Java (SimpleDateFormat) is very strict. It should complete missing parts with the current date. For example if I do not enter the year (only day and month) then the current year should be used. if the year is 08 then it should not parse 0008 because the current year pattern has 4 digits. Edit: I ...
I find it curious that the most obvious way to create Date objects in Java has been deprecated and appears to have been "substituted" with not so obvious to use lenient calendar. So... How do you check that a date given as a combination of day, month and year is a valid date? For instance a date 2008-02-31 (as in yyyy-mm-dd) would be invalid date.
I want to take two times (in seconds since epoch) and show the difference between the two in formats like: 2 minutes 1 hour, 15 minutes 3 hours, 9 minutes 1 minute ago 1 hour, 2 minutes ago How can I accomplish this??
Anyone know a simple way using java calendar to subtract X days to a date? Sry not being able to find any function which allows me to directly subtract X days to a date in java, if anyone could point me into the correct direction.
I want to get the Date in MM/DD/YY format from the timestamp. I search many but I dont get any Idea... I use below method but It not gives proper output final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(Long.parseLong(1306249409)); Log.d("Date--",""+cal.DAY_OF_MONTH); Log.d("Month--",""+cal.MONTH); Log.d("Year--",""+cal.YEAR); But its gives the output like below Date--...
How to define Global variables in Java ?
I have read the following discussions: http://stackoverflow.com/questions/538870/java-static-methods-best-practices , and http://stackoverflow.com/questions/658407/static-methods It seems that people in general would accept static methods, but are a little bit skeptical about it, for the following 2 reasons: They are hard to test. They violate the OO principal. (They are functions, not meth...
For instance: Calendar c = Calendar.getInstance(); DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); c.setTime( sdf.parse("31/12/2010")); out.println( c.get( Calendar.WEEK_OF_YEAR ) ); Prints 1 Same happens with Joda time. :)
Given today's time e.g. 2:24PM, how do I get it to round to 2:30PM? Similarly if the time was 2:17PM, how do I get it to round to 2:15PM?
strtotime() in PHP can do the following transformations: Inputs: strtotime(’2004-02-12T15:19:21+00:00′); strtotime(’Thu, 21 Dec 2000 16:01:07 +0200′); strtotime(’Monday, January 1st’); strtotime(’tomorrow’); strtotime(’-1 week 2 days 4 hours 2 seconds’); Outputs: 2004-02-12 07:02:21 2000-12-21 06:12:07 2009-01-01 12:01:00 2009-02-12 12:02:00 2009-02-06 09:02:41 Is there an easy way to ...
Suppose the following code is executed on the 22nd of August 2009 (a Saturday) Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); c.get(Calendar.DAY_OF_MONTH) will return 23. I'm interested in the conditions is would return 14 (last Sunday, rather than the next Sunday). Are there any rules associated with the direction Calendar will roll the DAY_OF_MON...
How do you get Hours and Minutes since Date.getHours and Date.getMinutes got deprecated? Note: The examples that I found in google search used the deprecated methods. Thank you.
In Ruby on Rails, there is a feature that allows you to take any Date and print out how "long ago" it was. For example: 8 minutes ago 8 hours ago 8 days ago 8 months ago 8 years ago Is there an easy way to do this in Java?
I have... Date start = new Date() ... ... ... Date stop = new Date() I'd like to get the years, months, days, hours, minutes and seconds ellapsed between these two dates. -- I'll refine the question. I just want to get the elapsed time, as an absolute measure, that is without taking into account leap years, the days of each month, etc. Thus I think it's impossible to get the years and...
When and how should we use a Constructor Foo bar = new Foo(); And When and how should we use getInstance() (static factory methods) Foo bar = Foo.getInstance(); What is the difference between these two, I always use the 1st way but when to use the 2nd way?? UPDATE 1 Say, I need to implement the class too and use .getInstance() from a different class. UPDATE 2 What do you guys mean by ...
What's the best way to get the current date/time?
   /*
    * Copyright 1996-2007 Sun Microsystems, Inc.  All Rights Reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code is free software; you can redistribute it and/or modify it
    * under the terms of the GNU General Public License version 2 only, as
    * published by the Free Software Foundation.  Sun designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Sun in the LICENSE file that accompanied this code.
   *
   * This code is distributed in the hope that it will be useful, but WITHOUT
   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   * version 2 for more details (a copy is included in the LICENSE file that
   * accompanied this code).
   *
   * You should have received a copy of the GNU General Public License version
   * 2 along with this work; if not, write to the Free Software Foundation,
   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   *
   * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   * CA 95054 USA or visit www.sun.com if you need additional information or
   * have any questions.
   */
  
  /*
   * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved
   * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
   *
   *   The original version of this source code and documentation is copyrighted
   * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
   * materials are provided under terms of a License Agreement between Taligent
   * and Sun. This technology is protected by multiple US and International
   * patents. This notice and attribution to Taligent may not be removed.
   *   Taligent is a registered trademark of Taligent, Inc.
   *
   */
  
  package java.util;
  
The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week. An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).

The class also provides additional fields and methods for implementing a concrete calendar system outside the package. Those fields and methods are defined as protected.

Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time:

     Calendar rightNow = Calendar.getInstance();
 

A Calendar object can produce all the calendar field values needed to implement the date-time formatting for a particular language and calendar style (for example, Japanese-Gregorian, Japanese-Traditional). Calendar defines the range of values returned by certain calendar fields, as well as their meaning. For example, the first month of the calendar system has value MONTH == JANUARY for all calendars. Other values are defined by the concrete subclass, such as ERA. See individual field documentation and subclass documentation for details.

Getting and Setting Calendar Field Values

The calendar field values can be set by calling the set methods. Any field values set in a Calendar will not be interpreted until it needs to calculate its time value (milliseconds from the Epoch) or values of the calendar fields. Calling the get, getTimeInMillis, getTime, add and roll involves such calculation.

Leniency

Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.

When a Calendar is in non-lenient mode, it throws an exception if there is any inconsistency in its calendar fields. For example, a GregorianCalendar always produces DAY_OF_MONTH values between 1 and the length of the month. A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set.

First Week

Calendar defines a locale-specific seven day week using two parameters: the first day of the week and the minimal days in first week (from 1 to 7). These numbers are taken from the locale resource data when a Calendar is constructed. They may also be specified explicitly through the methods for setting their values.

When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields, Calendar must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year. Weeks numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow it. Note that the normalized numbering returned by get() may be different. For example, a specific Calendar subclass may designate the week before week 1 of a year as week n of the previous year.

Calendar Fields Resolution

When computing a date and time from the calendar fields, there may be insufficient information for the computation (such as only year and month with no day of month), or there may be inconsistent information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15, 1996 is actually a Monday). Calendar will resolve calendar field values to determine the date and time in the following way.

If there is any conflict in calendar field values, Calendar gives priorities to calendar fields that have been set more recently. The following are the default combinations of the calendar fields. The most recent combination, as determined by the most recently set single field, will be used.

For the date fields:

 YEAR + MONTH + DAY_OF_MONTH
 YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
 YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
 YEAR + DAY_OF_YEAR
 YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
 
For the time of day fields:
 HOUR_OF_DAY
 AM_PM + HOUR
 

If there are any calendar fields whose values haven't been set in the selected field combination, Calendar uses their default values. The default value of each field may vary by concrete calendar systems. For example, in GregorianCalendar, the default of a field is the same as that of the start of the Epoch: i.e., YEAR = 1970, MONTH = JANUARY, DAY_OF_MONTH = 1, etc.

Note: There are certain possible ambiguities in interpretation of certain singular times, which are resolved in the following ways:

  1. 23:59 is the last minute of the day and 00:00 is the first minute of the next day. Thus, 23:59 on Dec 31, 1999 < 00:00 on Jan 1, 2000 < 00:01 on Jan 1, 2000.
  2. Although historically not precise, midnight also belongs to "am", and noon belongs to "pm", so on the same day, 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm

The date or time format strings are not part of the definition of a calendar, as those must be modifiable or overridable by the user at runtime. Use java.text.DateFormat to format dates.

Field Manipulation

The calendar fields can be changed using three methods: set(), add(), and roll().

set(f, value) changes calendar field f to value. In addition, it sets an internal member variable to indicate that calendar field f has been changed. Although calendar field f is changed immediately, the calendar's time value in milliseconds is not recomputed until the next call to get(), getTime(), getTimeInMillis(), add(), or roll() is made. Thus, multiple calls to set() do not trigger multiple, unnecessary computations. As a result of changing a calendar field using set(), other calendar fields may also change, depending on the calendar field, the calendar field value, and the calendar system. In addition, get(f) will not necessarily return value set by the call to the set method after the calendar fields have been recomputed. The specifics are determined by the concrete calendar class.

Example: Consider a GregorianCalendar originally set to August 31, 1999. Calling set(Calendar.MONTH, Calendar.SEPTEMBER) sets the date to September 31, 1999. This is a temporary internal representation that resolves to October 1, 1999 if getTime()is then called. However, a call to set(Calendar.DAY_OF_MONTH, 30) before the call to getTime() sets the date to September 30, 1999, since no recomputation occurs after set() itself.

add(f, delta) adds delta to field f. This is equivalent to calling set(f, get(f) + delta) with two adjustments:

Add rule 1. The value of field f after the call minus the value of field f before the call is delta, modulo any overflow that has occurred in field f. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.

Add rule 2. If a smaller field is expected to be invariant, but it is impossible for it to be equal to its prior value because of changes in its minimum or maximum after field f is changed or other constraints, such as time zone offset changes, then its value is adjusted to be as close as possible to its expected value. A smaller field represents a smaller unit of time. HOUR is a smaller field than DAY_OF_MONTH. No adjustment is made to smaller fields that are not expected to be invariant. The calendar system determines what fields are expected to be invariant.

In addition, unlike set(), add() forces an immediate recomputation of the calendar's milliseconds and all fields.

Example: Consider a GregorianCalendar originally set to August 31, 1999. Calling add(Calendar.MONTH, 13) sets the calendar to September 30, 2000. Add rule 1 sets the MONTH field to September, since adding 13 months to August gives September of the next year. Since DAY_OF_MONTH cannot be 31 in September in a GregorianCalendar, add rule 2 sets the DAY_OF_MONTH to 30, the closest possible value. Although it is a smaller field, DAY_OF_WEEK is not adjusted by rule 2, since it is expected to change when the month changes in a GregorianCalendar.

roll(f, delta) adds delta to field f without changing larger fields. This is equivalent to calling add(f, delta) with the following adjustment:

Roll rule. Larger fields are unchanged after the call. A larger field represents a larger unit of time. DAY_OF_MONTH is a larger field than HOUR.

Example: See GregorianCalendar.roll(int,int).

Usage model. To motivate the behavior of add() and roll(), consider a user interface component with increment and decrement buttons for the month, day, and year, and an underlying GregorianCalendar. If the interface reads January 31, 1999 and the user presses the month increment button, what should it read? If the underlying implementation uses set(), it might read March 3, 1999. A better result would be February 28, 1999. Furthermore, if the user presses the month increment button again, it should read March 31, 1999, not March 28, 1999. By saving the original date and using either add() or roll(), depending on whether larger fields should be affected, the user interface can behave as most users will intuitively expect.

Author(s):
Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
Since:
JDK1.1
See also:
java.lang.System.currentTimeMillis()
Date
GregorianCalendar
TimeZone
java.text.DateFormat
 
 public abstract class Calendar implements SerializableCloneableComparable<Calendar> {
 
     // Data flow in Calendar
     // ---------------------
 
     // The current time is represented in two ways by Calendar: as UTC
     // milliseconds from the epoch (1 January 1970 0:00 UTC), and as local
     // fields such as MONTH, HOUR, AM_PM, etc.  It is possible to compute the
     // millis from the fields, and vice versa.  The data needed to do this
     // conversion is encapsulated by a TimeZone object owned by the Calendar.
     // The data provided by the TimeZone object may also be overridden if the
     // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
     // keeps track of what information was most recently set by the caller, and
     // uses that to compute any other information as needed.
 
     // If the user sets the fields using set(), the data flow is as follows.
     // This is implemented by the Calendar subclass's computeTime() method.
     // During this process, certain fields may be ignored.  The disambiguation
     // algorithm for resolving which fields to pay attention to is described
     // in the class documentation.
 
     //   local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
     //           |
     //           | Using Calendar-specific algorithm
     //           V
     //   local standard millis
     //           |
     //           | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
     //           V
     //   UTC millis (in time data member)
 
     // If the user sets the UTC millis using setTime() or setTimeInMillis(),
     // the data flow is as follows.  This is implemented by the Calendar
     // subclass's computeFields() method.
 
     //   UTC millis (in time data member)
     //           |
     //           | Using TimeZone getOffset()
     //           V
     //   local standard millis
     //           |
     //           | Using Calendar-specific algorithm
     //           V
     //   local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
 
     // In general, a round trip from fields, through local and UTC millis, and
     // back out to fields is made when necessary.  This is implemented by the
     // complete() method.  Resolving a partial set of fields into a UTC millis
     // value allows all remaining fields to be generated from that value.  If
     // the Calendar is lenient, the fields are also renormalized to standard
     // ranges when they are regenerated.
 
    
Field number for get and set indicating the era, e.g., AD or BC in the Julian calendar. This is a calendar-specific value; see subclass documentation.

 
     public final static int ERA = 0;

    
Field number for get and set indicating the year. This is a calendar-specific value; see subclass documentation.
 
     public final static int YEAR = 1;

    
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

 
     public final static int MONTH = 2;

    
Field number for get and set indicating the week number within the current year. The first week of the year, as defined by getFirstDayOfWeek() and getMinimalDaysInFirstWeek(), has value 1. Subclasses define the value of WEEK_OF_YEAR for days before the first week of the year.

 
     public final static int WEEK_OF_YEAR = 3;

    
Field number for get and set indicating the week number within the current month. The first week of the month, as defined by getFirstDayOfWeek() and getMinimalDaysInFirstWeek(), has value 1. Subclasses define the value of WEEK_OF_MONTH for days before the first week of the month.

 
     public final static int WEEK_OF_MONTH = 4;

    
Field number for get and set indicating the day of the month. This is a synonym for DAY_OF_MONTH. The first day of the month has value 1.

See also:
DAY_OF_MONTH
 
     public final static int DATE = 5;

    
Field number for get and set indicating the day of the month. This is a synonym for DATE. The first day of the month has value 1.

See also:
DATE
 
     public final static int DAY_OF_MONTH = 5;

    
Field number for get and set indicating the day number within the current year. The first day of the year has value 1.
 
     public final static int DAY_OF_YEAR = 6;

    
Field number for get and set indicating the day of the week. This field takes values SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.

 
     public final static int DAY_OF_WEEK = 7;

    
Field number for get and set indicating the ordinal number of the day of the week within the current month. Together with the DAY_OF_WEEK field, this uniquely specifies a day within a month. Unlike WEEK_OF_MONTH and WEEK_OF_YEAR, this field's value does not depend on getFirstDayOfWeek() or getMinimalDaysInFirstWeek(). DAY_OF_MONTH 1 through 7 always correspond to DAY_OF_WEEK_IN_MONTH 1; 8 through 14 correspond to DAY_OF_WEEK_IN_MONTH 2, and so on. DAY_OF_WEEK_IN_MONTH 0 indicates the week before DAY_OF_WEEK_IN_MONTH 1. Negative values count back from the end of the month, so the last Sunday of a month is specified as DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1. Because negative values count backward they will usually be aligned differently within the month than positive values. For example, if a month has 31 days, DAY_OF_WEEK_IN_MONTH -1 will overlap DAY_OF_WEEK_IN_MONTH 5 and the end of 4.

 
     public final static int DAY_OF_WEEK_IN_MONTH = 8;

    
Field number for get and set indicating whether the HOUR is before or after noon. E.g., at 10:04:15.250 PM the AM_PM is PM.

See also:
AM
PM
HOUR
 
     public final static int AM_PM = 9;

    
Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.

 
     public final static int HOUR = 10;

    
Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.

See also:
HOUR
 
     public final static int HOUR_OF_DAY = 11;

    
Field number for get and set indicating the minute within the hour. E.g., at 10:04:15.250 PM the MINUTE is 4.
 
     public final static int MINUTE = 12;

    
Field number for get and set indicating the second within the minute. E.g., at 10:04:15.250 PM the SECOND is 15.
 
     public final static int SECOND = 13;

    
Field number for get and set indicating the millisecond within the second. E.g., at 10:04:15.250 PM the MILLISECOND is 250.
 
     public final static int MILLISECOND = 14;

    
Field number for get and set indicating the raw offset from GMT in milliseconds.

This field reflects the correct GMT offset value of the time zone of this Calendar if the TimeZone implementation subclass supports historical GMT offset changes.

 
     public final static int ZONE_OFFSET = 15;

    
Field number for get and set indicating the daylight savings offset in milliseconds.

This field reflects the correct daylight saving offset value of the time zone of this Calendar if the TimeZone implementation subclass supports historical Daylight Saving Time schedule changes.

 
     public final static int DST_OFFSET = 16;

    
The number of distinct fields recognized by get and set. Field numbers range from 0..FIELD_COUNT-1.
 
     public final static int FIELD_COUNT = 17;

    
Value of the DAY_OF_WEEK field indicating Sunday.
 
     public final static int SUNDAY = 1;

    
Value of the DAY_OF_WEEK field indicating Monday.
 
     public final static int MONDAY = 2;

    
Value of the DAY_OF_WEEK field indicating Tuesday.
 
     public final static int TUESDAY = 3;

    
Value of the DAY_OF_WEEK field indicating Wednesday.
 
     public final static int WEDNESDAY = 4;

    
Value of the DAY_OF_WEEK field indicating Thursday.
 
     public final static int THURSDAY = 5;

    
Value of the DAY_OF_WEEK field indicating Friday.
 
     public final static int FRIDAY = 6;

    
Value of the DAY_OF_WEEK field indicating Saturday.
 
     public final static int SATURDAY = 7;

    
Value of the MONTH field indicating the first month of the year in the Gregorian and Julian calendars.
 
     public final static int JANUARY = 0;

    
Value of the MONTH field indicating the second month of the year in the Gregorian and Julian calendars.
 
     public final static int FEBRUARY = 1;

    
Value of the MONTH field indicating the third month of the year in the Gregorian and Julian calendars.
 
     public final static int MARCH = 2;

    
Value of the MONTH field indicating the fourth month of the year in the Gregorian and Julian calendars.
 
     public final static int APRIL = 3;

    
Value of the MONTH field indicating the fifth month of the year in the Gregorian and Julian calendars.
 
     public final static int MAY = 4;

    
Value of the MONTH field indicating the sixth month of the year in the Gregorian and Julian calendars.
 
     public final static int JUNE = 5;

    
Value of the MONTH field indicating the seventh month of the year in the Gregorian and Julian calendars.
 
     public final static int JULY = 6;

    
Value of the MONTH field indicating the eighth month of the year in the Gregorian and Julian calendars.
 
     public final static int AUGUST = 7;

    
Value of the MONTH field indicating the ninth month of the year in the Gregorian and Julian calendars.
 
     public final static int SEPTEMBER = 8;

    
Value of the MONTH field indicating the tenth month of the year in the Gregorian and Julian calendars.
 
     public final static int OCTOBER = 9;

    
Value of the MONTH field indicating the eleventh month of the year in the Gregorian and Julian calendars.
 
     public final static int NOVEMBER = 10;

    
Value of the MONTH field indicating the twelfth month of the year in the Gregorian and Julian calendars.
 
     public final static int DECEMBER = 11;

    
Value of the MONTH field indicating the thirteenth month of the year. Although GregorianCalendar does not use this value, lunar calendars do.
 
     public final static int UNDECIMBER = 12;

    
Value of the AM_PM field indicating the period of the day from midnight to just before noon.
 
     public final static int AM = 0;

    
Value of the AM_PM field indicating the period of the day from noon to just before midnight.
 
     public final static int PM = 1;

    
A style specifier for getDisplayNames indicating names in all styles, such as "January" and "Jan".

Since:
1.6
See also:
SHORT
LONG
 
     public static final int ALL_STYLES = 0;

    
A style specifier for getDisplayName and getDisplayNames indicating a short name, such as "Jan".

Since:
1.6
See also:
LONG
 
     public static final int SHORT = 1;

    
A style specifier for getDisplayName and getDisplayNames indicating a long name, such as "January".

Since:
1.6
See also:
SHORT
 
     public static final int LONG = 2;
 
     // Internal notes:
     // Calendar contains two kinds of time representations: current "time" in
     // milliseconds, and a set of calendar "fields" representing the current time.
     // The two representations are usually in sync, but can get out of sync
     // as follows.
     // 1. Initially, no fields are set, and the time is invalid.
     // 2. If the time is set, all fields are computed and in sync.
     // 3. If a single field is set, the time is invalid.
     // Recomputation of the time and fields happens when the object needs
     // to return a result to the user, or use a result for a computation.
 
    
The calendar field values for the currently set time for this calendar. This is an array of FIELD_COUNT integers, with index values ERA through DST_OFFSET.

Serial:
 
     protected int           fields[];

    
The flags which tell if a specified calendar field for the calendar is set. A new object has no fields set. After the first call to a method which generates the fields, they all remain set after that. This is an array of FIELD_COUNT booleans, with index values ERA through DST_OFFSET.

Serial:
 
     protected boolean       isSet[];

    
Pseudo-time-stamps which specify when each field was set. There are two special values, UNSET and COMPUTED. Values from MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
 
     transient private int   stamp[];

    
The currently set time for this calendar, expressed in milliseconds after January 1, 1970, 0:00:00 GMT.

See also:
isTimeSet
Serial:
 
     protected long          time;

    
True if then the value of time is valid. The time is made invalid by a change to an item of field[].

See also:
time
Serial:
 
     protected boolean       isTimeSet;

    
True if fields[] are in sync with the currently set time. If false, then the next attempt to get the value of a field will force a recomputation of all fields from the current value of time.

Serial:
 
     protected boolean       areFieldsSet;

    
True if all fields have been set.

Serial:
 
     transient boolean       areAllFieldsSet;

    
True if this calendar allows out-of-range field values during computation of time from fields[].

 
     private boolean         lenient = true;

    
The TimeZone used by this calendar. Calendar uses the time zone data to translate between locale and GMT time.

Serial:
 
     private TimeZone        zone;

    
True if zone references to a shared TimeZone object.
 
     transient private boolean sharedZone = false;

    
The first day of the week, with possible values SUNDAY, MONDAY, etc. This is a locale-dependent value.

Serial:
 
     private int             firstDayOfWeek;

    
The number of days required for the first week in a month or year, with possible values from 1 to 7. This is a locale-dependent value.

Serial:
 
     private int             minimalDaysInFirstWeek;

    
Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek of a Locale.
 
     private static Hashtable<Localeint[]> cachedLocaleData = new Hashtable<Localeint[]>(3);
 
     // Special values of stamp[]
     
The corresponding fields[] has no value.
 
     private static final int        UNSET = 0;

    
The value of the corresponding fields[] has been calculated internally.
 
     private static final int        COMPUTED = 1;

    
The value of the corresponding fields[] has been set externally. Stamp values which are greater than 1 represents the (pseudo) time when the corresponding fields[] value was set.
 
     private static final int        MINIMUM_USER_STAMP = 2;

    
The mask value that represents all of the fields.
 
     static final int ALL_FIELDS = (1 << ) - 1;

    
The next available value for stamp[], an internal array. This actually should not be written out to the stream, and will probably be removed from the stream in the near future. In the meantime, a value of MINIMUM_USER_STAMP should be used.

Serial:
 
     private int             nextStamp = ;
 
     // the internal serial version which says which version was written
     // - 0 (default) for version up to JDK 1.1.5
     // - 1 for version from JDK 1.1.6, which writes a correct 'time' value
     //     as well as compatible values for other fields.  This is a
     //     transitional format.
     // - 2 (not implemented yet) a future version, in which fields[],
     //     areFieldsSet, and isTimeSet become transient, and isSet[] is
     //     removed. In JDK 1.1.6 we write a format compatible with version 2.
     static final int        currentSerialVersion = 1;

    
The version of the serialized data on the stream. Possible values:
0 or not present on stream
JDK 1.1.5 or earlier.
1
JDK 1.1.6 or later. Writes a correct 'time' value as well as compatible values for other fields. This is a transitional format.
When streaming out this class, the most recent format and the highest allowable serialVersionOnStream is written.

Since:
JDK1.1.6
Serial:
 
     private int             serialVersionOnStream = ;
 
     // Proclaim serialization compatibility with JDK 1.1
     static final long       serialVersionUID = -1807547505821590642L;
 
     // Mask values for calendar fields
     final static int ERA_MASK           = (1 << );
     final static int YEAR_MASK          = (1 << );
     final static int MONTH_MASK         = (1 << );
     final static int WEEK_OF_YEAR_MASK  = (1 << );
     final static int WEEK_OF_MONTH_MASK = (1 << );
     final static int DAY_OF_MONTH_MASK  = (1 << );
     final static int DATE_MASK          = ;
     final static int DAY_OF_YEAR_MASK   = (1 << );
     final static int DAY_OF_WEEK_MASK   = (1 << );
     final static int DAY_OF_WEEK_IN_MONTH_MASK  = (1 << );
     final static int AM_PM_MASK         = (1 << );
     final static int HOUR_MASK          = (1 << );
     final static int HOUR_OF_DAY_MASK   = (1 << );
     final static int MINUTE_MASK        = (1 << );
     final static int SECOND_MASK        = (1 << );
     final static int MILLISECOND_MASK   = (1 << );
     final static int ZONE_OFFSET_MASK   = (1 << );
     final static int DST_OFFSET_MASK    = (1 << );

    
Constructs a Calendar with the default time zone and locale.

 
     protected Calendar()
     {
         this(TimeZone.getDefaultRef(), Locale.getDefault());
          = true;
     }

    
Constructs a calendar with the specified time zone and locale.

Parameters:
zone the time zone to use
aLocale the locale for the week data
 
     protected Calendar(TimeZone zoneLocale aLocale)
     {
          = new int[];
          = new boolean[];
          = new int[];
 
         this. = zone;
         setWeekCountData(aLocale);
     }

    
Gets a calendar using the default time zone and locale. The Calendar returned is based on the current time in the default time zone with the default locale.

Returns:
a Calendar.
 
     public static Calendar getInstance()
     {
         Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault());
         cal.sharedZone = true;
         return cal;
     }

    
Gets a calendar using the specified time zone and default locale. The Calendar returned is based on the current time in the given time zone with the default locale.

Parameters:
zone the time zone to use
Returns:
a Calendar.
 
     public static Calendar getInstance(TimeZone zone)
     {
         return createCalendar(zone, Locale.getDefault());
     }

    
Gets a calendar using the default time zone and specified locale. The Calendar returned is based on the current time in the default time zone with the given locale.

Parameters:
aLocale the locale for the week data
Returns:
a Calendar.
 
     public static Calendar getInstance(Locale aLocale)
     {
         Calendar cal = createCalendar(TimeZone.getDefaultRef(), aLocale);
         cal.sharedZone = true;
         return cal;
     }

    
Gets a calendar with the specified time zone and locale. The Calendar returned is based on the current time in the given time zone with the given locale.

Parameters:
zone the time zone to use
aLocale the locale for the week data
Returns:
a Calendar.
    public static Calendar getInstance(TimeZone zone,
                                       Locale aLocale)
    {
        return createCalendar(zoneaLocale);
    }
    private static Calendar createCalendar(TimeZone zone,
                                           Locale aLocale)
    {
        // If the specified locale is a Thai locale, returns a BuddhistCalendar
        // instance.
        if ("th".equals(aLocale.getLanguage())
            && ("TH".equals(aLocale.getCountry()))) {
            return new sun.util.BuddhistCalendar(zoneaLocale);
        } else if ("JP".equals(aLocale.getVariant())
                   && "JP".equals(aLocale.getCountry())
                   && "ja".equals(aLocale.getLanguage())) {
            return new JapaneseImperialCalendar(zoneaLocale);
        }
        // else create the default calendar
        return new GregorianCalendar(zoneaLocale);
    }

    
Returns an array of all locales for which the getInstance methods of this class can return localized instances. The array returned must contain at least a Locale instance equal to Locale.US.

Returns:
An array of locales for which localized Calendar instances are available.
    public static synchronized Locale[] getAvailableLocales()
    {
        return DateFormat.getAvailableLocales();
    }

    
Converts the current calendar field values in fields[] to the millisecond time value time.

    protected abstract void computeTime();

    
Converts the current millisecond time value time to calendar field values in fields[]. This allows you to sync up the calendar field values with a new time that is set for the calendar. The time is not recomputed first; to recompute the time, then the fields, call the complete() method.

See also:
computeTime()
    protected abstract void computeFields();

    
Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Returns:
a Date representing the time value.
See also:
setTime(java.util.Date)
getTimeInMillis()
    public final Date getTime() {
        return new Date(getTimeInMillis());
    }

    
Sets this Calendar's time with the given Date.

Note: Calling setTime() with Date(Long.MAX_VALUE) or Date(Long.MIN_VALUE) may yield incorrect field values from get().

Parameters:
date the given Date.
See also:
getTime()
setTimeInMillis(long)
    public final void setTime(Date date) {
        setTimeInMillis(date.getTime());
    }

    
Returns this Calendar's time value in milliseconds.

Returns:
the current time as UTC milliseconds from the epoch.
See also:
getTime()
setTimeInMillis(long)
    public long getTimeInMillis() {
        if (!) {
            updateTime();
        }
        return ;
    }

    
Sets this Calendar's current time from the given long value.

Parameters:
millis the new time in UTC milliseconds from the epoch.
See also:
setTime(java.util.Date)
getTimeInMillis()
    public void setTimeInMillis(long millis) {
        // If we don't need to recalculate the calendar field values,
        // do nothing.
        if ( == millis &&  &&  && 
            && ( instanceof ZoneInfo) && !((ZoneInfo)).isDirty()) {
            return;
        }
         = millis;
         = true;
         = false;
        computeFields();
         =  = true;
    }

    
Returns the value of the given calendar field. In lenient mode, all calendar fields are normalized. In non-lenient mode, all calendar fields are validated and this method throws an exception if any calendar fields have out-of-range values. The normalization and validation are handled by the complete() method, which process is calendar system dependent.

Parameters:
field the given calendar field.
Returns:
the value for the given calendar field.
Throws:
java.lang.ArrayIndexOutOfBoundsException if the specified field is out of range (field < 0 || field >= FIELD_COUNT).
See also:
set(int,int)
complete()
    public int get(int field)
    {
        complete();
        return internalGet(field);
    }

    
Returns the value of the given calendar field. This method does not involve normalization or validation of the field value.

Parameters:
field the given calendar field.
Returns:
the value for the given calendar field.
See also:
get(int)
    protected final int internalGet(int field)
    {
        return [field];
    }

    
Sets the value of the given calendar field. This method does not affect any setting state of the field in this Calendar instance.

Throws:
java.lang.IndexOutOfBoundsException if the specified field is out of range (field < 0 || field >= FIELD_COUNT).
See also:
areFieldsSet
isTimeSet
areAllFieldsSet
set(int,int)
    final void internalSet(int fieldint value)
    {
        [field] = value;
    }

    
Sets the given calendar field to the given value. The value is not interpreted by this method regardless of the leniency mode.

Parameters:
field the given calendar field.
value the value to be set for the given calendar field.
Throws:
java.lang.ArrayIndexOutOfBoundsException if the specified field is out of range (field < 0 || field >= FIELD_COUNT). in non-lenient mode.
See also:
set(int,int,int)
set(int,int,int,int,int)
set(int,int,int,int,int,int)
get(int)
    public void set(int fieldint value)
    {
        if (isLenient() &&  && !) {
            computeFields();
        }
        internalSet(fieldvalue);
         = false;
         = false;
        [field] = true;
        [field] = ++;
        if ( == .) {
            adjustStamp();
        }
    }

    
Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH. Previous values of other calendar fields are retained. If this is not desired, call clear() first.

Parameters:
year the value used to set the YEAR calendar field.
month the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
date the value used to set the DAY_OF_MONTH calendar field.
See also:
set(int,int)
set(int,int,int,int,int)
set(int,int,int,int,int,int)
    public final void set(int yearint monthint date)
    {
        set(year);
        set(month);
        set(date);
    }

    
Sets the values for the calendar fields YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, and MINUTE. Previous values of other fields are retained. If this is not desired, call clear() first.

Parameters:
year the value used to set the YEAR calendar field.
month the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
date the value used to set the DAY_OF_MONTH calendar field.
hourOfDay the value used to set the HOUR_OF_DAY calendar field.
minute the value used to set the MINUTE calendar field.
See also:
set(int,int)
set(int,int,int)
set(int,int,int,int,int,int)
    public final void set(int yearint monthint dateint hourOfDayint minute)
    {
        set(year);
        set(month);
        set(date);
        set(hourOfDay);
        set(minute);
    }

    
Sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, and SECOND. Previous values of other fields are retained. If this is not desired, call clear() first.

Parameters:
year the value used to set the YEAR calendar field.
month the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
date the value used to set the DAY_OF_MONTH calendar field.
hourOfDay the value used to set the HOUR_OF_DAY calendar field.
minute the value used to set the MINUTE calendar field.
second the value used to set the SECOND calendar field.
See also:
set(int,int)
set(int,int,int)
set(int,int,int,int,int)
    public final void set(int yearint monthint dateint hourOfDayint minute,
                          int second)
    {
        set(year);
        set(month);
        set(date);
        set(hourOfDay);
        set(minute);
        set(second);
    }

    
Sets all the calendar field values and the time value (millisecond offset from the Epoch) of this Calendar undefined. This means that isSet(int) will return false for all the calendar fields, and the date and time calculations will treat the fields as if they had never been set. A Calendar implementation class may use its specific default field values for date/time calculations. For example, GregorianCalendar uses 1970 if the YEAR field value is undefined.

See also:
clear(int)
    public final void clear()
    {
        for (int i = 0; i < .; ) {
            [i] = [i] = 0; // UNSET == 0
            [i++] = false;
        }
         =  = false;
         = false;
    }

    
Sets the given calendar field value and the time value (millisecond offset from the Epoch) of this Calendar undefined. This means that isSet(int) will return false, and the date and time calculations will treat the field as if it had never been set. A Calendar implementation class may use the field's specific default value for date and time calculations.

The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(int,int) to reset the hour value.

Parameters:
field the calendar field to be cleared.
See also:
clear()
    public final void clear(int field)
    {
        [field] = 0;
        [field] = ;
        [field] = false;
         =  = false;
         = false;
    }

    
Determines if the given calendar field has a value set, including cases that the value has been set by internal fields calculations triggered by a get method call.

Returns:
true if the given calendar field has a value set; false otherwise.
    public final boolean isSet(int field)
    {
        return [field] != ;
    }

    
Returns the string representation of the calendar field value in the given style and locale. If no string representation is applicable, null is returned. This method calls get(field) to get the calendar field value if the string representation is applicable to the given calendar field.

For example, if this Calendar is a GregorianCalendar and its date is 2005-01-01, then the string representation of the MONTH field would be "January" in the long style in an English locale or "Jan" in the short style. However, no string representation would be available for the DAY_OF_MONTH field, and this method would return null.

The default implementation supports the calendar fields for which a java.text.DateFormatSymbols has names in the given locale.

Parameters:
field the calendar field for which the string representation is returned
style the style applied to the string representation; one of SHORT or LONG.
locale the locale for the string representation
Returns:
the string representation of the given field in the given style, or null if no string representation is applicable.
Throws:
java.lang.IllegalArgumentException if field or style is invalid, or if this Calendar is non-lenient and any of the calendar fields have invalid values
java.lang.NullPointerException if locale is null
Since:
1.6
    public String getDisplayName(int fieldint styleLocale locale) {
        if (!checkDisplayNameParams(fieldstylelocale,
                                    |||)) {
            return null;
        }
        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
        String[] strings = getFieldStrings(fieldstylesymbols);
        if (strings != null) {
            int fieldValue = get(field);
            if (fieldValue < strings.length) {
                return strings[fieldValue];
            }
        }
        return null;
    }

    
Returns a Map containing all names of the calendar field in the given style and locale and their corresponding field values. For example, if this Calendar is a GregorianCalendar, the returned map would contain "Jan" to JANUARY, "Feb" to FEBRUARY, and so on, in the short style in an English locale.

The values of other calendar fields may be taken into account to determine a set of display names. For example, if this Calendar is a lunisolar calendar system and the year value given by the YEAR field has a leap month, this method would return month names containing the leap month name, and month names are mapped to their values specific for the year.

The default implementation supports display names contained in a java.text.DateFormatSymbols. For example, if field is MONTH and style is ALL_STYLES, this method returns a Map containing all strings returned by java.text.DateFormatSymbols.getShortMonths() and java.text.DateFormatSymbols.getMonths().

Parameters:
field the calendar field for which the display names are returned
style the style applied to the display names; one of SHORT, LONG, or ALL_STYLES.
locale the locale for the display names
Returns:
a Map containing all display names in style and locale and their field values, or null if no display names are defined for field
Throws:
java.lang.IllegalArgumentException if field or style is invalid, or if this Calendar is non-lenient and any of the calendar fields have invalid values
java.lang.NullPointerException if locale is null
Since:
1.6
    public Map<StringIntegergetDisplayNames(int fieldint styleLocale locale) {
        if (!checkDisplayNameParams(fieldstylelocale,
                                    |||)) {
            return null;
        }
        // ALL_STYLES
        if (style == ) {
            Map<String,IntegershortNames = getDisplayNamesImpl(fieldlocale);
            if (field ==  || field == ) {
                return shortNames;
            }
            Map<String,IntegerlongNames = getDisplayNamesImpl(fieldlocale);
            if (shortNames == null) {
                return longNames;
            }
            if (longNames != null) {
                shortNames.putAll(longNames);
            }
            return shortNames;
        }
        // SHORT or LONG
        return getDisplayNamesImpl(fieldstylelocale);
    }
    private Map<String,IntegergetDisplayNamesImpl(int fieldint styleLocale locale) {
        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
        String[] strings = getFieldStrings(fieldstylesymbols);
        if (strings != null) {
            Map<String,Integernames = new HashMap<String,Integer>();
            for (int i = 0; i < strings.lengthi++) {
                if (strings[i].length() == 0) {
                    continue;
                }
                names.put(strings[i], i);
            }
            return names;
        }
        return null;
    }
    boolean checkDisplayNameParams(int fieldint styleint minStyleint maxStyle,
                                   Locale localeint fieldMask) {
        if (field < 0 || field >= . ||
            style < minStyle || style > maxStyle) {
            throw new IllegalArgumentException();
        }
        if (locale == null) {
            throw new NullPointerException();
        }
        return isFieldSet(fieldMaskfield);
    }
    private String[] getFieldStrings(int fieldint styleDateFormatSymbols symbols) {
        String[] strings = null;
        switch (field) {
        case :
            strings = symbols.getEras();
            break;
        case :
            strings = (style == ) ? symbols.getMonths() : symbols.getShortMonths();
            break;
        case :
            strings = (style == ) ? symbols.getWeekdays() : symbols.getShortWeekdays();
            break;
        case :
            strings = symbols.getAmPmStrings();
            break;
        }
        return strings;
    }

    
Fills in any unset fields in the calendar fields. First, the computeTime() method is called if the time value (millisecond offset from the Epoch) has not been calculated from calendar field values. Then, the computeFields() method is called to calculate all calendar field values.
    protected void complete()
    {
        if (!)
            updateTime();
        if (! || !) {
            computeFields(); // fills in unset fields
             =  = true;
        }
    }

    
Returns whether the value of the specified calendar field has been set externally by calling one of the setter methods rather than by the internal time calculation.

Returns:
true if the field has been set externally, false otherwise.
Throws:
java.lang.IndexOutOfBoundsException if the specified field is out of range (field < 0 || field >= FIELD_COUNT).
See also:
selectFields()
setFieldsComputed(int)
    final boolean isExternallySet(int field) {
        return [field] >= ;
    }

    
Returns a field mask (bit mask) indicating all calendar fields that have the state of externally or internally set.

Returns:
a bit mask indicating set state fields
    final int getSetStateFields() {
        int mask = 0;
        for (int i = 0; i < .i++) {
            if ([i] != ) {
                mask |= 1 << i;
            }
        }
        return mask;
    }

    
Sets the state of the specified calendar fields to computed. This state means that the specified calendar fields have valid values that have been set by internal time calculation rather than by calling one of the setter methods.

Parameters:
fieldMask the field to be marked as computed.
Throws:
java.lang.IndexOutOfBoundsException if the specified field is out of range (field < 0 || field >= FIELD_COUNT).
See also:
isExternallySet(int)
selectFields()
    final void setFieldsComputed(int fieldMask) {
        if (fieldMask == ) {
            for (int i = 0; i < .i++) {
                [i] = ;
                [i] = true;
            }
             =  = true;
        } else {
            for (int i = 0; i < .i++) {
                if ((fieldMask & 1) == 1) {
                    [i] = ;
                    [i] = true;
                } else {
                    if ( && ![i]) {
                         = false;
                    }
                }
                fieldMask >>>= 1;
            }
        }
    }

    
Sets the state of the calendar fields that are not specified by fieldMask to unset. If fieldMask specifies all the calendar fields, then the state of this Calendar becomes that all the calendar fields are in sync with the time value (millisecond offset from the Epoch).

Parameters:
fieldMask the field mask indicating which calendar fields are in sync with the time value.
Throws:
java.lang.IndexOutOfBoundsException if the specified field is out of range (field < 0 || field >= FIELD_COUNT).
See also:
isExternallySet(int)
selectFields()
    final void setFieldsNormalized(int fieldMask) {
        if (fieldMask != ) {
            for (int i = 0; i < .i++) {
                if ((fieldMask & 1) == 0) {
                    [i] = [i] = 0; // UNSET == 0
                    [i] = false;
                }
                fieldMask >>= 1;
            }
        }
        // Some or all of the fields are in sync with the
        // milliseconds, but the stamp values are not normalized yet.
         = true;
         = false;
    }

    
Returns whether the calendar fields are partially in sync with the time value or fully in sync but not stamp values are not normalized yet.
    final boolean isPartiallyNormalized() {
        return  && !;
    }

    
Returns whether the calendar fields are fully in sync with the time value.
    final boolean isFullyNormalized() {
        return  && ;
    }

    
Marks this Calendar as not sync'd.
    final void setUnnormalized() {
         =  = false;
    }

    
Returns whether the specified field is on in the fieldMask.
    static final boolean isFieldSet(int fieldMaskint field) {
        return (fieldMask & (1 << field)) != 0;
    }

    
Returns a field mask indicating which calendar field values to be used to calculate the time value. The calendar fields are returned as a bit mask, each bit of which corresponds to a field, i.e., the mask value of field is (1 << field). For example, 0x26 represents the YEAR, MONTH, and DAY_OF_MONTH fields (i.e., 0x26 is equal to (1<<YEAR)|(1<<MONTH)|(1<<DAY_OF_MONTH)).

This method supports the calendar fields resolution as described in the class description. If the bit mask for a given field is on and its field has not been set (i.e., isSet(field) is false), then the default value of the field has to be used, which case means that the field has been selected because the selected combination involves the field.

Returns:
a bit mask of selected fields
See also:
isExternallySet(int)
setInternallySetState(int)
    final int selectFields() {
        // This implementation has been taken from the GregorianCalendar class.
        // The YEAR field must always be used regardless of its SET
        // state because YEAR is a mandatory field to determine the date
        // and the default value (EPOCH_YEAR) may change through the
        // normalization process.
        int fieldMask = ;
        if ([] != ) {
            fieldMask |= ;
        }
        // Find the most recent group of fields specifying the day within
        // the year.  These may be any of the following combinations:
        //   MONTH + DAY_OF_MONTH
        //   MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
        //   MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
        //   DAY_OF_YEAR
        //   WEEK_OF_YEAR + DAY_OF_WEEK
        // We look for the most recent of the fields in each group to determine
        // the age of the group.  For groups involving a week-related field such
        // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
        // week-related field and the DAY_OF_WEEK must be set for the group as a
        // whole to be considered.  (See bug 4153860 - liu 7/24/98.)
        int dowStamp = [];
        int monthStamp = [];
        int domStamp = [];
        int womStamp = aggregateStamp([], dowStamp);
        int dowimStamp = aggregateStamp([], dowStamp);
        int doyStamp = [];
        int woyStamp = aggregateStamp([], dowStamp);
        int bestStamp = domStamp;
        if (womStamp > bestStamp) {
            bestStamp = womStamp;
        }
        if (dowimStamp > bestStamp) {
            bestStamp = dowimStamp;
        }
        if (doyStamp > bestStamp) {
            bestStamp = doyStamp;
        }
        if (woyStamp > bestStamp) {
            bestStamp = woyStamp;
        }
        /* No complete combination exists.  Look for WEEK_OF_MONTH,
         * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone.  Treat DAY_OF_WEEK alone
         * as DAY_OF_WEEK_IN_MONTH.
         */
        if (bestStamp == ) {
            womStamp = [];
            dowimStamp = Math.max([], dowStamp);
            woyStamp = [];
            bestStamp = Math.max(Math.max(womStampdowimStamp), woyStamp);
            /* Treat MONTH alone or no fields at all as DAY_OF_MONTH.  This may
             * result in bestStamp = domStamp = UNSET if no fields are set,
             * which indicates DAY_OF_MONTH.
             */
            if (bestStamp == ) {
                bestStamp = domStamp = monthStamp;
            }
        }
        if (bestStamp == domStamp ||
           (bestStamp == womStamp && [] >= []) ||
           (bestStamp == dowimStamp && [] >= [])) {
            fieldMask |= ;
            if (bestStamp == domStamp) {
                fieldMask |= ;
            } else {
                assert (bestStamp == womStamp || bestStamp == dowimStamp);
                if (dowStamp != ) {
                    fieldMask |= ;
                }
                if (womStamp == dowimStamp) {
                    // When they are equal, give the priority to
                    // WEEK_OF_MONTH for compatibility.
                    if ([] >= []) {
                        fieldMask |= ;
                    } else {
                        fieldMask |= ;
                    }
                } else {
                    if (bestStamp == womStamp) {
                        fieldMask |= ;
                    } else {
                        assert (bestStamp == dowimStamp);
                        if ([] != ) {
                            fieldMask |= ;
                        }
                    }
                }
            }
        } else {
            assert (bestStamp == doyStamp || bestStamp == woyStamp ||
                    bestStamp == );
            if (bestStamp == doyStamp) {
                fieldMask |= ;
            } else {
                assert (bestStamp == woyStamp);
                if (dowStamp != ) {
                    fieldMask |= ;
                }
                fieldMask |= ;
            }
        }
        // Find the best set of fields specifying the time of day.  There
        // are only two possibilities here; the HOUR_OF_DAY or the
        // AM_PM and the HOUR.
        int hourOfDayStamp = [];
        int hourStamp = aggregateStamp([], []);
        bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
        // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)
        if (bestStamp == ) {
            bestStamp = Math.max([], []);
        }
        // Hours
        if (bestStamp != ) {
            if (bestStamp == hourOfDayStamp) {
                fieldMask |= ;
            } else {
                fieldMask |= ;
                if ([] != ) {
                    fieldMask |= ;
                }
            }
        }
        if ([] != ) {
            fieldMask |= ;
        }
        if ([] != ) {
            fieldMask |= ;
        }
        if ([] != ) {
            fieldMask |= ;
        }
        if ([] >= ) {
                fieldMask |= ;
        }
        if ([] >= ) {
            fieldMask |= ;
        }
        return fieldMask;
    }

    
Returns the pseudo-time-stamp for two fields, given their individual pseudo-time-stamps. If either of the fields is unset, then the aggregate is unset. Otherwise, the aggregate is the later of the two stamps.
    private static final int aggregateStamp(int stamp_aint stamp_b) {
        if (stamp_a ==  || stamp_b == ) {
            return ;
        }
        return (stamp_a > stamp_b) ? stamp_a : stamp_b;
    }

    
Compares this Calendar to the specified Object. The result is true if and only if the argument is a Calendar object of the same calendar system that represents the same time value (millisecond offset from the Epoch) under the same Calendar parameters as this object.

The Calendar parameters are the values represented by the isLenient, getFirstDayOfWeek, getMinimalDaysInFirstWeek and getTimeZone methods. If there is any difference in those parameters between the two Calendars, this method returns false.

Use the compareTo method to compare only the time values.

Parameters:
obj the object to compare with.
Returns:
true if this object is equal to obj; false otherwise.
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        try {
            Calendar that = (Calendar)obj;
            return compareTo(getMillisOf(that)) == 0 &&
                 == that.lenient &&
                 == that.firstDayOfWeek &&
                 == that.minimalDaysInFirstWeek &&
                .equals(that.zone);
        } catch (Exception e) {
            // Note: GregorianCalendar.computeTime throws
            // IllegalArgumentException if the ERA value is invalid
            // even it's in lenient mode.
        }
        return false;
    }

    
Returns a hash code for this calendar.

Returns:
a hash code value for this object.
Since:
1.2
    public int hashCode() {
        // 'otheritems' represents the hash code for the previous versions.
        int otheritems = ( ? 1 : 0)
            | ( << 1)
            | ( << 4)
            | (.hashCode() << 7);
        long t = getMillisOf(this);
        return (intt ^ (int)(t >> 32) ^ otheritems;
    }

    
Returns whether this Calendar represents a time before the time represented by the specified Object. This method is equivalent to:
compareTo(when) < 0
if and only if when is a Calendar instance. Otherwise, the method returns false.

Parameters:
when the Object to be compared
Returns:
true if the time of this Calendar is before the time represented by when; false otherwise.
See also:
compareTo(java.util.Calendar)
    public boolean before(Object when) {
        return when instanceof Calendar
            && compareTo((Calendar)when) < 0;
    }

    
Returns whether this Calendar represents a time after the time represented by the specified Object. This method is equivalent to:
compareTo(when) > 0
if and only if when is a Calendar instance. Otherwise, the method returns false.

Parameters:
when the Object to be compared
Returns:
true if the time of this Calendar is after the time represented by when; false otherwise.
See also:
compareTo(java.util.Calendar)
    public boolean after(Object when) {
        return when instanceof Calendar
            && compareTo((Calendar)when) > 0;
    }

    
Compares the time values (millisecond offsets from the Epoch) represented by two Calendar objects.

Parameters:
anotherCalendar the Calendar to be compared.
Returns:
the value 0 if the time represented by the argument is equal to the time represented by this Calendar; a value less than 0 if the time of this Calendar is before the time represented by the argument; and a value greater than 0 if the time of this Calendar is after the time represented by the argument.
Throws:
java.lang.NullPointerException if the specified Calendar is null.
java.lang.IllegalArgumentException if the time value of the specified Calendar object can't be obtained due to any invalid calendar values.
Since:
1.5
    public int compareTo(Calendar anotherCalendar) {
        return compareTo(getMillisOf(anotherCalendar));
    }

    
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:

add(Calendar.DAY_OF_MONTH, -5).

Parameters:
field the calendar field.
amount the amount of date or time to be added to the field.
See also:
roll(int,int)
set(int,int)
    abstract public void add(int fieldint amount);

    
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields. For example, to roll the current date up by one day, you can achieve it by calling:

roll(Calendar.DATE, true). When rolling on the year or Calendar.YEAR field, it will roll the year value in the range between 1 and the value returned by calling getMaximum(Calendar.YEAR). When rolling on the month or Calendar.MONTH field, other fields like date might conflict and, need to be changed. For instance, rolling the month on the date 01/31/96 will result in 02/29/96. When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will roll the hour value in the range between 0 and 23, which is zero-based.

Parameters:
field the time field.
up indicates if the value of the specified time field is to be rolled up or rolled down. Use true if rolling up, false otherwise.
See also:
add(int,int)
set(int,int)
    abstract public void roll(int fieldboolean up);

    
Adds the specified (signed) amount to the specified calendar field without changing larger fields. A negative amount means to roll down.

NOTE: This default implementation on Calendar just repeatedly calls the version of roll() that rolls by one unit. This may not always do the right thing. For example, if the DAY_OF_MONTH field is 31, rolling through February will leave it set to 28. The GregorianCalendar version of this function takes care of this problem. Other subclasses should also provide overrides of this function that do the right thing.

Parameters:
field the calendar field.
amount the signed amount to add to the calendar field.
Since:
1.2
See also:
roll(int,boolean)
add(int,int)
set(int,int)
    public void roll(int fieldint amount)
    {
        while (amount > 0) {
            roll(fieldtrue);
            amount--;
        }
        while (amount < 0) {
            roll(fieldfalse);
            amount++;
        }
    }

    
Sets the time zone with the given time zone value.

Parameters:
value the given time zone.
    public void setTimeZone(TimeZone value)
    {
         = value;
         = false;
        /* Recompute the fields from the time using the new zone.  This also
         * works if isTimeSet is false (after a call to set()).  In that case
         * the time will be computed from the fields using the new zone, then
         * the fields will get recomputed from that.  Consider the sequence of
         * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
         * Is cal set to 1 o'clock EST or 1 o'clock PST?  Answer: PST.  More
         * generally, a call to setTimeZone() affects calls to set() BEFORE AND
         * AFTER it up to the next call to complete().
         */
         =  = false;
    }

    
Gets the time zone.

Returns:
the time zone object associated with this calendar.
    public TimeZone getTimeZone()
    {
        // If the TimeZone object is shared by other Calendar instances, then
        // create a clone.
        if () {
             = (TimeZone.clone();
             = false;
        }
        return ;
    }

    
Returns the time zone (without cloning).
    TimeZone getZone() {
        return ;
    }

    
Sets the sharedZone flag to shared.
    void setZoneShared(boolean shared) {
         = shared;
    }

    
Specifies whether or not date/time interpretation is to be lenient. With lenient interpretation, a date such as "February 942, 1996" will be treated as being equivalent to the 941st day after February 1, 1996. With strict (non-lenient) interpretation, such dates will cause an exception to be thrown. The default is lenient.

Parameters:
lenient true if the lenient mode is to be turned on; false if it is to be turned off.
See also:
isLenient()
java.text.DateFormat.setLenient(boolean)
    public void setLenient(boolean lenient)
    {
        this. = lenient;
    }

    
Tells whether date/time interpretation is to be lenient.

Returns:
true if the interpretation mode of this calendar is lenient; false otherwise.
See also:
setLenient(boolean)
    public boolean isLenient()
    {
        return ;
    }

    
Sets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.

Parameters:
value the given first day of the week.
See also:
getFirstDayOfWeek()
getMinimalDaysInFirstWeek()
    public void setFirstDayOfWeek(int value)
    {
        if ( == value) {
            return;
        }
         = value;
        invalidateWeekFields();
    }

    
Gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.

Returns:
the first day of the week.
See also:
setFirstDayOfWeek(int)
getMinimalDaysInFirstWeek()
    public int getFirstDayOfWeek()
    {
        return ;
    }

    
Sets what the minimal days required in the first week of the year are; For example, if the first week is defined as one that contains the first day of the first month of a year, call this method with value 1. If it must be a full week, use value 7.

Parameters:
value the given minimal days required in the first week of the year.
See also:
getMinimalDaysInFirstWeek()
    public void setMinimalDaysInFirstWeek(int value)
    {
        if ( == value) {
            return;
        }
         = value;
        invalidateWeekFields();
    }

    
Gets what the minimal days required in the first week of the year are; e.g., if the first week is defined as one that contains the first day of the first month of a year, this method returns 1. If the minimal days required must be a full week, this method returns 7.

Returns:
the minimal days required in the first week of the year.
See also:
setMinimalDaysInFirstWeek(int)
    public int getMinimalDaysInFirstWeek()
    {
        return ;
    }

    
Returns the minimum value for the given calendar field of this Calendar instance. The minimum value is defined as the smallest value returned by the get method for any possible time value. The minimum value depends on calendar system specific parameters of the instance.

Parameters:
field the calendar field.
Returns:
the minimum value for the given calendar field.
See also:
getMaximum(int)
getGreatestMinimum(int)
getLeastMaximum(int)
getActualMinimum(int)
getActualMaximum(int)
    abstract public int getMinimum(int field);

    
Returns the maximum value for the given calendar field of this Calendar instance. The maximum value is defined as the largest value returned by the get method for any possible time value. The maximum value depends on calendar system specific parameters of the instance.

Parameters:
field the calendar field.
Returns:
the maximum value for the given calendar field.
See also:
getMinimum(int)
getGreatestMinimum(int)
getLeastMaximum(int)
getActualMinimum(int)
getActualMaximum(int)
    abstract public int getMaximum(int field);

    
Returns the highest minimum value for the given calendar field of this Calendar instance. The highest minimum value is defined as the largest value returned by getActualMinimum(int) for any possible time value. The greatest minimum value depends on calendar system specific parameters of the instance.

Parameters:
field the calendar field.
Returns:
the highest minimum value for the given calendar field.
See also:
getMinimum(int)
getMaximum(int)
getLeastMaximum(int)
getActualMinimum(int)
getActualMaximum(int)
    abstract public int getGreatestMinimum(int field);

    
Returns the lowest maximum value for the given calendar field of this Calendar instance. The lowest maximum value is defined as the smallest value returned by getActualMaximum(int) for any possible time value. The least maximum value depends on calendar system specific parameters of the instance. For example, a Calendar for the Gregorian calendar system returns 28 for the DAY_OF_MONTH field, because the 28th is the last day of the shortest month of this calendar, February in a common year.

Parameters:
field the calendar field.
Returns:
the lowest maximum value for the given calendar field.
See also:
getMinimum(int)
getMaximum(int)
getGreatestMinimum(int)
getActualMinimum(int)
getActualMaximum(int)
    abstract public int getLeastMaximum(int field);

    
Returns the minimum value that the specified calendar field could have, given the time value of this Calendar.

The default implementation of this method uses an iterative algorithm to determine the actual minimum value for the calendar field. Subclasses should, if possible, override this with a more efficient implementation - in many cases, they can simply return getMinimum().

Parameters:
field the calendar field
Returns:
the minimum of the given calendar field for the time value of this Calendar
Since:
1.2
See also:
getMinimum(int)
getMaximum(int)
getGreatestMinimum(int)
getLeastMaximum(int)
getActualMaximum(int)
    public int getActualMinimum(int field) {
        int fieldValue = getGreatestMinimum(field);
        int endValue = getMinimum(field);
        // if we know that the minimum value is always the same, just return it
        if (fieldValue == endValue) {
            return fieldValue;
        }
        // clone the calendar so we don't mess with the real one, and set it to
        // accept anything for the field values
        Calendar work = (Calendar)this.clone();
        work.setLenient(true);
        // now try each value from getLeastMaximum() to getMaximum() one by one until
        // we get a value that normalizes to another value.  The last value that
        // normalizes to itself is the actual minimum for the current date
        int result = fieldValue;
        do {
            work.set(fieldfieldValue);
            if (work.get(field) != fieldValue) {
                break;
            } else {
                result = fieldValue;
                fieldValue--;
            }
        } while (fieldValue >= endValue);
        return result;
    }

    
Returns the maximum value that the specified calendar field could have, given the time value of this Calendar. For example, the actual maximum value of the MONTH field is 12 in some years, and 13 in other years in the Hebrew calendar system.

The default implementation of this method uses an iterative algorithm to determine the actual maximum value for the calendar field. Subclasses should, if possible, override this with a more efficient implementation.

Parameters:
field the calendar field
Returns:
the maximum of the given calendar field for the time value of this Calendar
Since:
1.2
See also:
getMinimum(int)
getMaximum(int)
getGreatestMinimum(int)
getLeastMaximum(int)
getActualMinimum(int)
    public int getActualMaximum(int field) {
        int fieldValue = getLeastMaximum(field);
        int endValue = getMaximum(field);
        // if we know that the maximum value is always the same, just return it.
        if (fieldValue == endValue) {
            return fieldValue;
        }
        // clone the calendar so we don't mess with the real one, and set it to
        // accept anything for the field values.
        Calendar work = (Calendar)this.clone();
        work.setLenient(true);
        // if we're counting weeks, set the day of the week to Sunday.  We know the
        // last week of a month or year will contain the first day of the week.
        if (field ==  || field == )
            work.set();
        // now try each value from getLeastMaximum() to getMaximum() one by one until
        // we get a value that normalizes to another value.  The last value that
        // normalizes to itself is the actual maximum for the current date
        int result = fieldValue;
        do {
            work.set(fieldfieldValue);
            if (work.get(field) != fieldValue) {
                break;
            } else {
                result = fieldValue;
                fieldValue++;
            }
        } while (fieldValue <= endValue);
        return result;
    }

    
Creates and returns a copy of this object.

Returns:
a copy of this object.
    public Object clone()
    {
        try {
            Calendar other = (Calendarsuper.clone();
            other.fields = new int[];
            other.isSet = new boolean[];
            other.stamp = new int[];
            for (int i = 0; i < i++) {
                other.fields[i] = [i];
                other.stamp[i] = [i];
                other.isSet[i] = [i];
            }
            other.zone = (TimeZone.clone();
            return other;
        }
        catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError();
        }
    }
    private static final String[] FIELD_NAME = {
        "ERA""YEAR""MONTH""WEEK_OF_YEAR""WEEK_OF_MONTH""DAY_OF_MONTH",
        "DAY_OF_YEAR""DAY_OF_WEEK""DAY_OF_WEEK_IN_MONTH""AM_PM""HOUR",
        "HOUR_OF_DAY""MINUTE""SECOND""MILLISECOND""ZONE_OFFSET",
        "DST_OFFSET"
    };

    
Returns the name of the specified calendar field.

Parameters:
field the calendar field
Returns:
the calendar field name
Throws:
java.lang.IndexOutOfBoundsException if field is negative, equal to or greater then FIELD_COUNT.
    static final String getFieldName(int field) {
        return [field];
    }

    
Return a string representation of this calendar. This method is intended to be used only for debugging purposes, and the format of the returned string may vary between implementations. The returned string may be empty but may not be null.

Returns:
a string representation of this calendar.
    public String toString() {
        // NOTE: BuddhistCalendar.toString() interprets the string
        // produced by this method so that the Gregorian year number
        // is substituted by its B.E. year value. It relies on
        // "...,YEAR=<year>,..." or "...,YEAR=?,...".
        StringBuilder buffer = new StringBuilder(800);
        buffer.append(getClass().getName()).append('[');
        appendValue(buffer"time");
        buffer.append(",areFieldsSet=").append();
        buffer.append(",areAllFieldsSet=").append();
        buffer.append(",lenient=").append();
        buffer.append(",zone=").append();
        appendValue(buffer",firstDayOfWeek"true, (long);
        appendValue(buffer",minimalDaysInFirstWeek"true, (long);
        for (int i = 0; i < ; ++i) {
            buffer.append(',');
            appendValue(buffer[i], isSet(i), (long[i]);
        }
        buffer.append(']');
        return buffer.toString();
    }
    // =======================privates===============================
    private static final void appendValue(StringBuilder sbString itemboolean validlong value) {
        sb.append(item).append('=');
        if (valid) {
            sb.append(value);
        } else {
            sb.append('?');
        }
    }

    
Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent. They are used to figure out the week count for a specific date for a given locale. These must be set when a Calendar is constructed.

Parameters:
desiredLocale the given locale.
    private void setWeekCountData(Locale desiredLocale)
    {
        /* try to get the Locale data from the cache */
        int[] data = .get(desiredLocale);
        if (data == null) {  /* cache miss */
            ResourceBundle bundle = LocaleData.getCalendarData(desiredLocale);
            data = new int[2];
            data[0] = Integer.parseInt(bundle.getString("firstDayOfWeek"));
            data[1] = Integer.parseInt(bundle.getString("minimalDaysInFirstWeek"));
            .put(desiredLocaledata);
        }
         = data[0];
         = data[1];
    }

    
Recomputes the time and updates the status fields isTimeSet and areFieldsSet. Callers should check isTimeSet and only call this method if isTimeSet is false.
    private void updateTime() {
        computeTime();
        // The areFieldsSet and areAllFieldsSet values are no longer
        // controlled here (as of 1.5).
         = true;
    }
    private int compareTo(long t) {
        long thisTime = getMillisOf(this);
        return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
    }
    private static final long getMillisOf(Calendar calendar) {
        if (calendar.isTimeSet) {
            return calendar.time;
        }
        Calendar cal = (Calendarcalendar.clone();
        cal.setLenient(true);
        return cal.getTimeInMillis();
    }

    
Adjusts the stamp[] values before nextStamp overflow. nextStamp is set to the next stamp value upon the return.
    private final void adjustStamp() {
        int max = ;
        int newStamp = ;
        for (;;) {
            int min = .;
            for (int i = 0; i < .i++) {
                int v = [i];
                if (v >= newStamp && min > v) {
                    min = v;
                }
                if (max < v) {
                    max = v;
                }
            }
            if (max != min && min == .) {
                break;
            }
            for (int i = 0; i < .i++) {
                if ([i] == min) {
                    [i] = newStamp;
                }
            }
            newStamp++;
            if (min == max) {
                break;
            }
        }
         = newStamp;
    }

    
Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the new parameter value if they have been calculated internally.
    private void invalidateWeekFields()
    {
        if ([] !=  &&
            [] != ) {
            return;
        }
        // We have to check the new values of these fields after changing
        // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values
        // have been changed, then set the new values. (4822110)
        Calendar cal = (Calendarclone();
        cal.setLenient(true);
        cal.clear();
        cal.clear();
        if ([] == ) {
            int weekOfMonth = cal.get();
            if ([] != weekOfMonth) {
                [] = weekOfMonth;
            }
        }
        if ([] == ) {
            int weekOfYear = cal.get();
            if ([] != weekOfYear) {
                [] = weekOfYear;
            }
        }
    }

    
Save the state of this object to a stream (i.e., serialize it). Ideally, Calendar would only write out its state data and the current time, and not write any field data out, such as fields[], isTimeSet, areFieldsSet, and isSet[]. nextStamp also should not be part of the persistent state. Unfortunately, this didn't happen before JDK 1.1 shipped. To be compatible with JDK 1.1, we will always have to write out the field values and state flags. However, nextStamp can be removed from the serialization stream; this will probably happen in the near future.
    private void writeObject(ObjectOutputStream stream)
         throws IOException
    {
        // Try to compute the time correctly, for the future (stream
        // version 2) in which we don't write out fields[] or isSet[].
        if (!) {
            try {
                updateTime();
            }
            catch (IllegalArgumentException e) {}
        }
        // If this Calendar has a ZoneInfo, save it and set a
        // SimpleTimeZone equivalent (as a single DST schedule) for
        // backward compatibility.
        TimeZone savedZone = null;
        if ( instanceof ZoneInfo) {
            SimpleTimeZone stz = ((ZoneInfo)).getLastRuleInstance();
            if (stz == null) {
                stz = new SimpleTimeZone(.getRawOffset(), .getID());
            }
            savedZone = ;
             = stz;
        }
        // Write out the 1.1 FCS object.
        stream.defaultWriteObject();
        // Write out the ZoneInfo object
        // 4802409: we write out even if it is null, a temporary workaround
        // the real fix for bug 4844924 in corba-iiop
        stream.writeObject(savedZone);
        if (savedZone != null) {
             = savedZone;
        }
    }
    private static class CalendarAccessControlContext {
        private static final AccessControlContext INSTANCE;
        static {
            RuntimePermission perm = new RuntimePermission("accessClassInPackage.sun.util.calendar");
            PermissionCollection perms = perm.newPermissionCollection();
            perms.add(perm);
             = new AccessControlContext(new ProtectionDomain[] {
                                                    new ProtectionDomain(nullperms)
                                                });
        }
    }

    
Reconstitutes this object from a stream (i.e., deserialize it).
    private void readObject(ObjectInputStream stream)
         throws IOExceptionClassNotFoundException
    {
        final ObjectInputStream input = stream;
        input.defaultReadObject();
         = new int[];
        // Starting with version 2 (not implemented yet), we expect that
        // fields[], isSet[], isTimeSet, and areFieldsSet may not be
        // streamed out anymore.  We expect 'time' to be correct.
        if ( >= 2)
        {
             = true;
            if ( == null = new int[];
            if ( == null = new boolean[];
        }
        else if ( >= 0)
        {
            for (int i=0; i<; ++i)
                [i] = [i] ?  : ;
        }
        // If there's a ZoneInfo object, use it for zone.
        ZoneInfo zi = null;
        try {
            zi = AccessController.doPrivileged(
                    new PrivilegedExceptionAction<ZoneInfo>() {
                        public ZoneInfo run() throws Exception {
                            return (ZoneInfoinput.readObject();
                        }
                    },
                    .);
        } catch (PrivilegedActionException pae) {
            Exception e = pae.getException();
            if (!(e instanceof OptionalDataException)) {
                if (e instanceof RuntimeException) {
                    throw (RuntimeExceptione;
                } else if (e instanceof IOException) {
                    throw (IOExceptione;
                } else if (e instanceof ClassNotFoundException) {
                    throw (ClassNotFoundExceptione;
                }
                throw new RuntimeException(e);
            }
        }
        if (zi != null) {
             = zi;
        }
        // If the deserialized object has a SimpleTimeZone, try to
        // replace it with a ZoneInfo equivalent (as of 1.4) in order
        // to be compatible with the SimpleTimeZone-based
        // implementation as much as possible.
        if ( instanceof SimpleTimeZone) {
            String id = .getID();
            TimeZone tz = TimeZone.getTimeZone(id);
            if (tz != null && tz.hasSameRules() && tz.getID().equals(id)) {
                 = tz;
            }
        }
    }
New to GrepCode? Check out our FAQ X