Source for java.util.Calendar

   1: /* Calendar.java --
   2:    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006,  
   3:    Free Software Foundation, Inc.
   4: 
   5: This file is part of GNU Classpath.
   6: 
   7: GNU Classpath is free software; you can redistribute it and/or modify
   8: it under the terms of the GNU General Public License as published by
   9: the Free Software Foundation; either version 2, or (at your option)
  10: any later version.
  11: 
  12: GNU Classpath is distributed in the hope that it will be useful, but
  13: WITHOUT ANY WARRANTY; without even the implied warranty of
  14: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15: General Public License for more details.
  16: 
  17: You should have received a copy of the GNU General Public License
  18: along with GNU Classpath; see the file COPYING.  If not, write to the
  19: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  20: 02110-1301 USA.
  21: 
  22: Linking this library statically or dynamically with other modules is
  23: making a combined work based on this library.  Thus, the terms and
  24: conditions of the GNU General Public License cover the whole
  25: combination.
  26: 
  27: As a special exception, the copyright holders of this library give you
  28: permission to link this library with independent modules to produce an
  29: executable, regardless of the license terms of these independent
  30: modules, and to copy and distribute the resulting executable under
  31: terms of your choice, provided that you also meet, for each linked
  32: independent module, the terms and conditions of the license of that
  33: module.  An independent module is a module which is not derived from
  34: or based on this library.  If you modify this library, you may extend
  35: this exception to your version of the library, but you are not
  36: obligated to do so.  If you do not wish to do so, delete this
  37: exception statement from your version. */
  38: 
  39: 
  40: package java.util;
  41: 
  42: import java.io.IOException;
  43: import java.io.ObjectInputStream;
  44: import java.io.ObjectOutputStream;
  45: import java.io.Serializable;
  46: 
  47: import java.lang.reflect.Constructor;
  48: import java.lang.reflect.InvocationTargetException;
  49: 
  50: import java.text.DateFormatSymbols;
  51: 
  52: /**
  53:  * This class is an abstract base class for Calendars, which can be
  54:  * used to convert between <code>Date</code> objects and a set of
  55:  * integer fields which represent <code>YEAR</code>,
  56:  * <code>MONTH</code>, <code>DAY</code>, etc.  The <code>Date</code>
  57:  * object represents a time in milliseconds since the Epoch. <br>
  58:  *
  59:  * This class is locale sensitive.  To get the Object matching the
  60:  * current locale you can use <code>getInstance</code>.  You can even provide
  61:  * a locale or a timezone.  <code>getInstance</code> returns currently
  62:  * a <code>GregorianCalendar</code> for the current date. <br>
  63:  *
  64:  * If you want to convert a date from the Year, Month, Day, DayOfWeek,
  65:  * etc.  Representation to a <code>Date</code>-Object, you can create
  66:  * a new Calendar with <code>getInstance()</code>,
  67:  * <code>clear()</code> all fields, <code>set(int,int)</code> the
  68:  * fields you need and convert it with <code>getTime()</code>. <br>
  69:  *
  70:  * If you want to convert a <code>Date</code>-object to the Calendar
  71:  * representation, create a new Calendar, assign the
  72:  * <code>Date</code>-Object with <code>setTime()</code>, and read the
  73:  * fields with <code>get(int)</code>. <br>
  74:  *
  75:  * When computing the date from time fields, it may happen, that there
  76:  * are either two few fields set, or some fields are inconsistent.  This
  77:  * cases will handled in a calendar specific way.  Missing fields are
  78:  * replaced by the fields of the epoch: 1970 January 1 00:00. <br>
  79:  *
  80:  * To understand, how the day of year is computed out of the fields
  81:  * look at the following table.  It is traversed from top to bottom,
  82:  * and for the first line all fields are set, that line is used to
  83:  * compute the day. <br>
  84:  *
  85:  *
  86: <pre>month + day_of_month
  87: month + week_of_month + day_of_week
  88: month + day_of_week_of_month + day_of_week
  89: day_of_year
  90: day_of_week + week_of_year</pre>
  91:  *
  92:  * The hour_of_day-field takes precedence over the ampm and
  93:  * hour_of_ampm fields. <br>
  94:  *
  95:  * <STRONG>Note:</STRONG> This can differ for non-Gregorian calendar. <br>
  96:  *
  97:  * To convert a calendar to a human readable form and vice versa,  use
  98:  * the <code>java.text.DateFormat</code> class. <br>
  99:  *
 100:  * Other useful things you can do with an calendar, is
 101:  * <code>roll</code>ing fields (that means increase/decrease a
 102:  * specific field by one, propagating overflows), or
 103:  * <code>add</code>ing/substracting a fixed amount to a field.
 104:  *
 105:  * @author Aaron M. Renn (arenn@urbanophile.com)
 106:  * @author Jochen Hoenicke (Jochen.Hoenicke@Informatik.Uni-Oldenburg.de)
 107:  * @author Warren Levy (warrenl@cygnus.com)
 108:  * @author Jeff Sturm (jsturm@one-point.com)
 109:  * @author Tom Tromey (tromey@redhat.com)
 110:  * @author Bryce McKinlay (mckinlay@redhat.com)
 111:  * @author Ingo Proetel (proetel@aicas.com)
 112:  * @author Jerry Quinn (jlquinn@optonline.net)
 113:  * @author Jeroen Frijters (jeroen@frijters.net)
 114:  * @author Noa Resare (noa@resare.com)
 115:  * @author Sven de Marothy (sven@physto.se)
 116:  * @author David Gilbert (david.gilbert@object-refinery.com)
 117:  * @author Olivier Jolly (olivier.jolly@pcedev.com)
 118:  * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
 119:  * @see Date
 120:  * @see GregorianCalendar
 121:  * @see TimeZone
 122:  * @see java.text.DateFormat
 123:  */
 124: public abstract class Calendar
 125:   implements Serializable, Cloneable, Comparable<Calendar>
 126: {
 127:   /**
 128:    * Constant representing the era time field.
 129:    */
 130:   public static final int ERA = 0;
 131: 
 132:   /**
 133:    * Constant representing the year time field.
 134:    */
 135:   public static final int YEAR = 1;
 136: 
 137:   /**
 138:    * Constant representing the month time field.  This field
 139:    * should contain one of the JANUARY,...,DECEMBER constants below.
 140:    */
 141:   public static final int MONTH = 2;
 142: 
 143:   /**
 144:    * Constant representing the week of the year field.
 145:    * @see #setFirstDayOfWeek(int)
 146:    */
 147:   public static final int WEEK_OF_YEAR = 3;
 148: 
 149:   /**
 150:    * Constant representing the week of the month time field.
 151:    * @see #setFirstDayOfWeek(int)
 152:    */
 153:   public static final int WEEK_OF_MONTH = 4;
 154: 
 155:   /**
 156:    * Constant representing the day time field, synonym for DAY_OF_MONTH.
 157:    */
 158:   public static final int DATE = 5;
 159: 
 160:   /**
 161:    * Constant representing the day time field.
 162:    */
 163:   public static final int DAY_OF_MONTH = 5;
 164: 
 165:   /**
 166:    * Constant representing the day of year time field.  This is
 167:    * 1 for the first day in month.
 168:    */
 169:   public static final int DAY_OF_YEAR = 6;
 170: 
 171:   /**
 172:    * Constant representing the day of week time field.  This field
 173:    * should contain one of the SUNDAY,...,SATURDAY constants below.
 174:    */
 175:   public static final int DAY_OF_WEEK = 7;
 176: 
 177:   /**
 178:    * Constant representing the day-of-week-in-month field.  For
 179:    * instance this field contains 2 for the second thursday in a
 180:    * month.  If you give a negative number here, the day will count
 181:    * from the end of the month.
 182:    */
 183:   public static final int DAY_OF_WEEK_IN_MONTH = 8;
 184: 
 185:   /**
 186:    * Constant representing the part of the day for 12-hour clock.  This
 187:    * should be one of AM or PM.
 188:    */
 189:   public static final int AM_PM = 9;
 190: 
 191:   /**
 192:    * Constant representing the hour time field for 12-hour clock.
 193:    */
 194:   public static final int HOUR = 10;
 195: 
 196:   /**
 197:    * Constant representing the hour of day time field for 24-hour clock.
 198:    */
 199:   public static final int HOUR_OF_DAY = 11;
 200: 
 201:   /**
 202:    * Constant representing the minute of hour time field.
 203:    */
 204:   public static final int MINUTE = 12;
 205: 
 206:   /**
 207:    * Constant representing the second time field.
 208:    */
 209:   public static final int SECOND = 13;
 210: 
 211:   /**
 212:    * Constant representing the millisecond time field.
 213:    */
 214:   public static final int MILLISECOND = 14;
 215: 
 216:   /**
 217:    * Constant representing the time zone offset time field for the
 218:    * time given in the other fields.  It is measured in
 219:    * milliseconds.  The default is the offset of the time zone.
 220:    */
 221:   public static final int ZONE_OFFSET = 15;
 222: 
 223:   /**
 224:    * Constant representing the daylight saving time offset in
 225:    * milliseconds.  The default is the value given by the time zone.
 226:    */
 227:   public static final int DST_OFFSET = 16;
 228: 
 229:   /**
 230:    * Number of time fields.
 231:    */
 232:   public static final int FIELD_COUNT = 17;
 233: 
 234:   /**
 235:    * Constant representing Sunday.
 236:    */
 237:   public static final int SUNDAY = 1;
 238: 
 239:   /**
 240:    * Constant representing Monday.
 241:    */
 242:   public static final int MONDAY = 2;
 243: 
 244:   /**
 245:    * Constant representing Tuesday.
 246:    */
 247:   public static final int TUESDAY = 3;
 248: 
 249:   /**
 250:    * Constant representing Wednesday.
 251:    */
 252:   public static final int WEDNESDAY = 4;
 253: 
 254:   /**
 255:    * Constant representing Thursday.
 256:    */
 257:   public static final int THURSDAY = 5;
 258: 
 259:   /**
 260:    * Constant representing Friday.
 261:    */
 262:   public static final int FRIDAY = 6;
 263: 
 264:   /**
 265:    * Constant representing Saturday.
 266:    */
 267:   public static final int SATURDAY = 7;
 268: 
 269:   /**
 270:    * Constant representing January.
 271:    */
 272:   public static final int JANUARY = 0;
 273: 
 274:   /**
 275:    * Constant representing February.
 276:    */
 277:   public static final int FEBRUARY = 1;
 278: 
 279:   /**
 280:    * Constant representing March.
 281:    */
 282:   public static final int MARCH = 2;
 283: 
 284:   /**
 285:    * Constant representing April.
 286:    */
 287:   public static final int APRIL = 3;
 288: 
 289:   /**
 290:    * Constant representing May.
 291:    */
 292:   public static final int MAY = 4;
 293: 
 294:   /**
 295:    * Constant representing June.
 296:    */
 297:   public static final int JUNE = 5;
 298: 
 299:   /**
 300:    * Constant representing July.
 301:    */
 302:   public static final int JULY = 6;
 303: 
 304:   /**
 305:    * Constant representing August.
 306:    */
 307:   public static final int AUGUST = 7;
 308: 
 309:   /**
 310:    * Constant representing September.
 311:    */
 312:   public static final int SEPTEMBER = 8;
 313: 
 314:   /**
 315:    * Constant representing October.
 316:    */
 317:   public static final int OCTOBER = 9;
 318: 
 319:   /**
 320:    * Constant representing November.
 321:    */
 322:   public static final int NOVEMBER = 10;
 323: 
 324:   /**
 325:    * Constant representing December.
 326:    */
 327:   public static final int DECEMBER = 11;
 328: 
 329:   /**
 330:    * Constant representing Undecimber. This is an artificial name useful
 331:    * for lunar calendars.
 332:    */
 333:   public static final int UNDECIMBER = 12;
 334: 
 335:   /**
 336:    * Useful constant for 12-hour clock.
 337:    */
 338:   public static final int AM = 0;
 339: 
 340:   /**
 341:    * Useful constant for 12-hour clock.
 342:    */
 343:   public static final int PM = 1;
 344: 
 345:   /**
 346:    * A style specifier for {@link #getDisplayNames(int,int,Locale)}
 347:    * stating that names should be returned in both long and short variants.
 348:    *
 349:    * @since 1.6
 350:    * @see #SHORT
 351:    * @see #LONG
 352:    */
 353:   public static final int ALL_STYLES = 0;
 354: 
 355:   /**
 356:    * A style specifier for {@link #getDisplayName(int,int,Locale)}
 357:    * and {@link #getDisplayNames(int,int,Locale)} stating that names
 358:    * should be returned in their short variant if applicable.
 359:    *
 360:    * @since 1.6
 361:    */
 362:   public static final int SHORT = 1;
 363: 
 364:   /**
 365:    * A style specifier for {@link #getDisplayName(int,int,Locale)}
 366:    * and {@link #getDisplayNames(int,int,Locale)} stating that names
 367:    * should be returned in their long variant if applicable.
 368:    *
 369:    * @since 1.6
 370:    */
 371:   public static final int LONG = 2;
 372: 
 373:   /**
 374:    * The time fields.  The array is indexed by the constants YEAR to
 375:    * DST_OFFSET.
 376:    * @serial
 377:    */
 378:   protected int[] fields = new int[FIELD_COUNT];
 379: 
 380:   /**
 381:    * The flags which tell if the fields above have a value.
 382:    * @serial
 383:    */
 384:   protected boolean[] isSet = new boolean[FIELD_COUNT];
 385: 
 386:   /**
 387:    * The time in milliseconds since the epoch.
 388:    * @serial
 389:    */
 390:   protected long time;
 391: 
 392:   /**
 393:    * Tells if the above field has a valid value.
 394:    * @serial
 395:    */
 396:   protected boolean isTimeSet;
 397: 
 398:   /**
 399:    * Tells if the fields have a valid value.  This superseeds the isSet
 400:    * array.
 401:    * @serial
 402:    */
 403:   protected boolean areFieldsSet;
 404: 
 405:   /**
 406:    * The time zone of this calendar.  Used by sub classes to do UTC / local
 407:    * time conversion.  Sub classes can access this field with getTimeZone().
 408:    * @serial
 409:    */
 410:   private TimeZone zone;
 411: 
 412:   /**
 413:    * This is the default calendar class, that is returned on
 414:    * java.util.Calendar.getInstance().
 415:    * XXX - this isn't localized anywhere, is it?
 416:    * @see java.util.Calendar#getInstance()
 417:    */
 418:   private static final String calendarClassName = "java.util.GregorianCalendar";
 419: 
 420:   /**
 421:    * Specifies if the date/time interpretation should be lenient.
 422:    * If the flag is set, a date such as "February 30, 1996" will be
 423:    * treated as the 29th day after the February 1.  If this flag
 424:    * is false, such dates will cause an exception.
 425:    * @serial
 426:    */
 427:   private boolean lenient;
 428: 
 429:   /**
 430:    * Sets what the first day of week is.  This is used for
 431:    * WEEK_OF_MONTH and WEEK_OF_YEAR fields.
 432:    * @serial
 433:    */
 434:   private int firstDayOfWeek;
 435: 
 436:   /**
 437:    * Sets how many days are required in the first week of the year.
 438:    * If the first day of the year should be the first week you should
 439:    * set this value to 1.  If the first week must be a full week, set
 440:    * it to 7.
 441:    * @serial
 442:    */
 443:   private int minimalDaysInFirstWeek;
 444: 
 445:   /**
 446:    * Is set to true if DST_OFFSET is explicitly set. In that case
 447:    * it's value overrides the value computed from the current
 448:    * time and the timezone.
 449:    */
 450:   private boolean explicitDSTOffset = false;
 451: 
 452:   /**
 453:    * The version of the serialized data on the stream.
 454:    * <dl><dt>0 or not present</dt>
 455:    * <dd> JDK 1.1.5 or later.</dd>
 456:    * <dt>1</dt>
 457:    * <dd>JDK 1.1.6 or later.  This always writes a correct `time' value
 458:    * on the stream, as well as the other fields, to be compatible with
 459:    * earlier versions</dd></dl>
 460:    * @since JDK1.1.6
 461:    * @serial
 462:    */
 463:   private int serialVersionOnStream = 1;
 464: 
 465:   /**
 466:    * XXX - I have not checked the compatibility.  The documentation of
 467:    * the serialized-form is quite hairy...
 468:    */
 469:   static final long serialVersionUID = -1807547505821590642L;
 470: 
 471:   /**
 472:    * The name of the resource bundle. Used only by getBundle()
 473:    */
 474:   private static final String bundleName = "gnu.java.locale.LocaleInformation";
 475: 
 476:   /**
 477:    * get resource bundle:
 478:    * The resources should be loaded via this method only. Iff an application
 479:    * uses this method, the resourcebundle is required.
 480:    */
 481:   private static ResourceBundle getBundle(Locale locale)
 482:   {
 483:     return ResourceBundle.getBundle(bundleName, locale,
 484:                                     ClassLoader.getSystemClassLoader());
 485:   }
 486: 
 487:   /**
 488:    * Constructs a new Calendar with the default time zone and the default
 489:    * locale.
 490:    */
 491:   protected Calendar()
 492:   {
 493:     this(TimeZone.getDefault(), Locale.getDefault());
 494:   }
 495: 
 496:   /**
 497:    * Constructs a new Calendar with the given time zone and the given
 498:    * locale.
 499:    * @param zone a time zone.
 500:    * @param locale a locale.
 501:    */
 502:   protected Calendar(TimeZone zone, Locale locale)
 503:   {
 504:     this.zone = zone;
 505:     lenient = true;
 506:     String[] days = { "", "sun", "mon", "tue", "wed", "thu", "fri", "sat" };
 507: 
 508:     ResourceBundle rb = getBundle(locale);
 509:     String min = (String) rb.getObject("minNumberOfDaysInFirstWeek");
 510:     String first = (String) rb.getObject("firstDayOfWeek");
 511:     try
 512:       {
 513:     if (min != null)
 514:       minimalDaysInFirstWeek = Integer.parseInt(min);
 515:       }
 516:     catch (NumberFormatException ex)
 517:       {
 518:     minimalDaysInFirstWeek = 1;
 519:       }
 520: 
 521:     firstDayOfWeek = 1;
 522:     if (first != null)
 523:       for (int i = 0; i < 8; i++)
 524:     if (days[i].equals(first))
 525:       firstDayOfWeek = i;
 526: 
 527:     clear();
 528:   }
 529: 
 530:   /**
 531:    * Creates a calendar representing the actual time, using the default
 532:    * time zone and locale.
 533:    * 
 534:    * @return The new calendar.
 535:    */
 536:   public static synchronized Calendar getInstance()
 537:   {
 538:     return getInstance(TimeZone.getDefault(), Locale.getDefault());
 539:   }
 540: 
 541:   /**
 542:    * Creates a calendar representing the actual time, using the given
 543:    * time zone and the default locale.
 544:    * 
 545:    * @param zone a time zone (<code>null</code> not permitted).
 546:    * 
 547:    * @return The new calendar.
 548:    * 
 549:    * @throws NullPointerException if <code>zone</code> is <code>null</code>.
 550:    */
 551:   public static synchronized Calendar getInstance(TimeZone zone)
 552:   {
 553:     return getInstance(zone, Locale.getDefault());
 554:   }
 555: 
 556:   /**
 557:    * Creates a calendar representing the actual time, using the default
 558:    * time zone and the given locale.
 559:    * 
 560:    * @param locale a locale (<code>null</code> not permitted).
 561:    * 
 562:    * @return The new calendar.
 563:    * 
 564:    * @throws NullPointerException if <code>locale</code> is <code>null</code>.
 565:    */
 566:   public static synchronized Calendar getInstance(Locale locale)
 567:   {
 568:     return getInstance(TimeZone.getDefault(), locale);
 569:   }
 570: 
 571:   /**
 572:    * Cache of locale->calendar-class mappings. This avoids having to do a ResourceBundle
 573:    * lookup for every getInstance call.
 574:    */
 575:   private static HashMap<Locale,Class> cache = new HashMap<Locale,Class>();
 576: 
 577:   /** Preset argument types for calendar-class constructor lookup.  */
 578:   private static Class[] ctorArgTypes = new Class[]
 579:                                         {
 580:                                           TimeZone.class, Locale.class
 581:                                         };
 582: 
 583:   /**
 584:    * Creates a calendar representing the actual time, using the given
 585:    * time zone and locale.
 586:    * 
 587:    * @param zone a time zone (<code>null</code> not permitted).
 588:    * @param locale a locale (<code>null</code> not permitted).
 589:    * 
 590:    * @return The new calendar.
 591:    * 
 592:    * @throws NullPointerException if <code>zone</code> or <code>locale</code>
 593:    *     is <code>null</code>.
 594:    */
 595:   public static synchronized Calendar getInstance(TimeZone zone, Locale locale)
 596:   {
 597:     Class calendarClass = cache.get(locale);
 598:     Throwable exception = null;
 599: 
 600:     try
 601:       {
 602:     if (calendarClass == null)
 603:       {
 604:         calendarClass = Class.forName(calendarClassName);
 605:         if (Calendar.class.isAssignableFrom(calendarClass))
 606:           cache.put(locale, calendarClass);
 607:       }
 608: 
 609:     // GregorianCalendar is by far the most common case. Optimize by 
 610:     // avoiding reflection.
 611:     if (calendarClass == GregorianCalendar.class)
 612:       return new GregorianCalendar(zone, locale);
 613: 
 614:     if (Calendar.class.isAssignableFrom(calendarClass))
 615:       {
 616:         Constructor ctor = calendarClass.getConstructor(ctorArgTypes);
 617:         return (Calendar) ctor.newInstance(new Object[] { zone, locale });
 618:       }
 619:       }
 620:     catch (ClassNotFoundException ex)
 621:       {
 622:     exception = ex;
 623:       }
 624:     catch (IllegalAccessException ex)
 625:       {
 626:     exception = ex;
 627:       }
 628:     catch (NoSuchMethodException ex)
 629:       {
 630:     exception = ex;
 631:       }
 632:     catch (InstantiationException ex)
 633:       {
 634:     exception = ex;
 635:       }
 636:     catch (InvocationTargetException ex)
 637:       {
 638:     exception = ex;
 639:       }
 640: 
 641:     throw new RuntimeException("Error instantiating calendar for locale "
 642:                                + locale, exception);
 643:   }
 644: 
 645:   /**
 646:    * Gets the set of locales for which a Calendar is available.
 647:    * @exception MissingResourceException if locale data couldn't be found.
 648:    * @return the set of locales.
 649:    */
 650:   public static synchronized Locale[] getAvailableLocales()
 651:   {
 652:     ResourceBundle rb = getBundle(new Locale("", ""));
 653:     return (Locale[]) rb.getObject("availableLocales");
 654:   }
 655: 
 656:   /**
 657:    * Converts the time field values (<code>fields</code>) to
 658:    * milliseconds since the epoch UTC (<code>time</code>).  Override
 659:    * this method if you write your own Calendar.  */
 660:   protected abstract void computeTime();
 661: 
 662:   /**
 663:    * Converts the milliseconds since the epoch UTC
 664:    * (<code>time</code>) to time fields
 665:    * (<code>fields</code>). Override this method if you write your
 666:    * own Calendar.
 667:    */
 668:   protected abstract void computeFields();
 669: 
 670:   /**
 671:    * Converts the time represented by this object to a
 672:    * <code>Date</code>-Object.
 673:    * @return the Date.
 674:    */
 675:   public final Date getTime()
 676:   {
 677:     if (! isTimeSet)
 678:       computeTime();
 679:     return new Date(time);
 680:   }
 681: 
 682:   /**
 683:    * Sets this Calendar's time to the given Date.  All time fields
 684:    * are invalidated by this method.
 685:    * 
 686:    * @param date  the date (<code>null</code> not permitted).
 687:    * 
 688:    * @throws NullPointerException if <code>date</code> is <code>null</code>.
 689:    */
 690:   public final void setTime(Date date)
 691:   {
 692:     setTimeInMillis(date.getTime());
 693:   }
 694: 
 695:   /**
 696:    * Returns the time represented by this Calendar.
 697:    * @return the time in milliseconds since the epoch.
 698:    * @specnote This was made public in 1.4.
 699:    */
 700:   public long getTimeInMillis()
 701:   {
 702:     if (! isTimeSet)
 703:       computeTime();
 704:     return time;
 705:   }
 706: 
 707:   /**
 708:    * Sets this Calendar's time to the given Time.  All time fields
 709:    * are invalidated by this method.
 710:    * @param time the time in milliseconds since the epoch
 711:    * @specnote This was made public in 1.4.
 712:    */
 713:   public void setTimeInMillis(long time)
 714:   {
 715:     clear();
 716:     this.time = time;
 717:     isTimeSet = true;
 718:     computeFields();
 719:   }
 720: 
 721:   /**
 722:    * Gets the value of the specified field.  They are recomputed
 723:    * if they are invalid.
 724:    * @param field the time field. One of the time field constants.
 725:    * @return the value of the specified field
 726:    * @throws ArrayIndexOutOfBoundsException if the field is outside
 727:    *         the valid range.  The value of field must be >= 0 and
 728:    *         <= <code>FIELD_COUNT</code>.
 729:    * @specnote Not final since JDK 1.4
 730:    */
 731:   public int get(int field)
 732:   {
 733:     // If the requested field is invalid, force all fields to be recomputed.
 734:     if (! isSet[field])
 735:       areFieldsSet = false;
 736:     complete();
 737:     return fields[field];
 738:   }
 739: 
 740:   /**
 741:    * Gets the value of the specified field. This method doesn't
 742:    * recompute the fields, if they are invalid.
 743:    * @param field the time field. One of the time field constants.
 744:    * @return the value of the specified field, undefined if
 745:    * <code>areFieldsSet</code> or <code>isSet[field]</code> is false.
 746:    * @throws ArrayIndexOutOfBoundsException if the field is outside
 747:    *         the valid range.  The value of field must be >= 0 and
 748:    *         <= <code>FIELD_COUNT</code>.
 749:    */
 750:   protected final int internalGet(int field)
 751:   {
 752:     return fields[field];
 753:   }
 754: 
 755:   /**
 756:    * Sets the time field with the given value.  This does invalidate
 757:    * the time in milliseconds.
 758:    * @param field the time field. One of the time field constants
 759:    * @param value the value to be set.
 760:    * @throws ArrayIndexOutOfBoundsException if field is outside
 761:    *         the valid range.  The value of field must be >= 0 and
 762:    *         <= <code>FIELD_COUNT</code>.
 763:    * @specnote Not final since JDK 1.4
 764:    */
 765:   public void set(int field, int value)
 766:   {
 767:     if (isTimeSet)
 768:       for (int i = 0; i < FIELD_COUNT; i++)
 769:     isSet[i] = false;
 770:     isTimeSet = false;
 771:     fields[field] = value;
 772:     isSet[field] = true;
 773: 
 774:     // The five valid date patterns, in order of priority
 775:     // 1  YEAR + MONTH + DAY_OF_MONTH
 776:     // 2  YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
 777:     // 3  YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
 778:     // 4  YEAR + DAY_OF_YEAR
 779:     // 5  YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
 780:     switch (field)
 781:       {
 782:       case MONTH: // pattern 1,2 or 3
 783:     isSet[DAY_OF_YEAR] = false;
 784:     isSet[WEEK_OF_YEAR] = false;
 785:     break;
 786:       case DAY_OF_MONTH: // pattern 1
 787:     isSet[YEAR] = true;
 788:     isSet[MONTH] = true;
 789:     isSet[WEEK_OF_MONTH] = true;
 790:     isSet[DAY_OF_WEEK] = false;
 791:     isSet[DAY_OF_WEEK_IN_MONTH] = false;
 792:     isSet[DAY_OF_YEAR] = false;
 793:     isSet[WEEK_OF_YEAR] = false;
 794:     break;
 795:       case WEEK_OF_MONTH: // pattern 2
 796:     if (! isSet[DAY_OF_WEEK])
 797:       fields[DAY_OF_WEEK] = getFirstDayOfWeek();
 798:     isSet[YEAR] = true;
 799:     isSet[MONTH] = true;
 800:     isSet[DAY_OF_WEEK] = true;
 801:     isSet[DAY_OF_MONTH] = false;
 802:     isSet[DAY_OF_WEEK_IN_MONTH] = false;
 803:     isSet[DAY_OF_YEAR] = false;
 804:     isSet[WEEK_OF_YEAR] = false;
 805:     break;
 806:       case DAY_OF_WEEK_IN_MONTH: // pattern 3
 807:     if (! isSet[DAY_OF_WEEK])
 808:       fields[DAY_OF_WEEK] = getFirstDayOfWeek();
 809:     isSet[YEAR] = true;
 810:     isSet[MONTH] = true;
 811:     isSet[DAY_OF_WEEK] = true;
 812:     isSet[DAY_OF_YEAR] = false;
 813:     isSet[DAY_OF_MONTH] = false;
 814:     isSet[WEEK_OF_MONTH] = false;
 815:     isSet[WEEK_OF_YEAR] = false;
 816:     break;
 817:       case DAY_OF_YEAR: // pattern 4
 818:     isSet[YEAR] = true;
 819:     isSet[MONTH] = false;
 820:     isSet[WEEK_OF_MONTH] = false;
 821:     isSet[DAY_OF_MONTH] = false;
 822:     isSet[DAY_OF_WEEK] = false;
 823:     isSet[WEEK_OF_YEAR] = false;
 824:     isSet[DAY_OF_WEEK_IN_MONTH] = false;
 825:     break;
 826:       case WEEK_OF_YEAR: // pattern 5
 827:     if (! isSet[DAY_OF_WEEK])
 828:       fields[DAY_OF_WEEK] = getFirstDayOfWeek();
 829:     isSet[YEAR] = true;
 830:     isSet[DAY_OF_WEEK] = true;
 831:     isSet[MONTH] = false;
 832:     isSet[DAY_OF_MONTH] = false;
 833:     isSet[WEEK_OF_MONTH] = false;
 834:     isSet[DAY_OF_YEAR] = false;
 835:     isSet[DAY_OF_WEEK_IN_MONTH] = false;
 836:     break;
 837:       case AM_PM:
 838:     isSet[HOUR] = true;
 839:     isSet[HOUR_OF_DAY] = false;
 840:     break;
 841:       case HOUR_OF_DAY:
 842:     isSet[AM_PM] = false;
 843:     isSet[HOUR] = false;
 844:     break;
 845:       case HOUR:
 846:     isSet[AM_PM] = true;
 847:     isSet[HOUR_OF_DAY] = false;
 848:     break;
 849:       case DST_OFFSET:
 850:     explicitDSTOffset = true;
 851:       }
 852: 
 853:     // May have crossed over a DST boundary.
 854:     if (! explicitDSTOffset && (field != DST_OFFSET && field != ZONE_OFFSET))
 855:       isSet[DST_OFFSET] = false;
 856:   }
 857: 
 858:   /**
 859:    * Sets the fields for year, month, and date
 860:    * @param year the year.
 861:    * @param month the month, one of the constants JANUARY..UNDICEMBER.
 862:    * @param date the day of the month
 863:    */
 864:   public final void set(int year, int month, int date)
 865:   {
 866:     isTimeSet = false;
 867:     fields[YEAR] = year;
 868:     fields[MONTH] = month;
 869:     fields[DATE] = date;
 870:     isSet[YEAR] = isSet[MONTH] = isSet[DATE] = true;
 871:     isSet[WEEK_OF_YEAR] = false;
 872:     isSet[DAY_OF_YEAR] = false;
 873:     isSet[WEEK_OF_MONTH] = false;
 874:     isSet[DAY_OF_WEEK] = false;
 875:     isSet[DAY_OF_WEEK_IN_MONTH] = false;
 876:     isSet[ERA] = false;
 877: 
 878:     if (! explicitDSTOffset)
 879:       isSet[DST_OFFSET] = false; // May have crossed a DST boundary.
 880:   }
 881: 
 882:   /**
 883:    * Sets the fields for year, month, date, hour, and minute
 884:    * @param year the year.
 885:    * @param month the month, one of the constants JANUARY..UNDICEMBER.
 886:    * @param date the day of the month
 887:    * @param hour the hour of day.
 888:    * @param minute the minute.
 889:    */
 890:   public final void set(int year, int month, int date, int hour, int minute)
 891:   {
 892:     set(year, month, date);
 893:     fields[HOUR_OF_DAY] = hour;
 894:     fields[MINUTE] = minute;
 895:     isSet[HOUR_OF_DAY] = isSet[MINUTE] = true;
 896:     isSet[AM_PM] = false;
 897:     isSet[HOUR] = false;
 898:   }
 899: 
 900:   /**
 901:    * Sets the fields for year, month, date, hour, and minute
 902:    * @param year the year.
 903:    * @param month the month, one of the constants JANUARY..UNDICEMBER.
 904:    * @param date the day of the month
 905:    * @param hour the hour of day.
 906:    * @param minute the minute.
 907:    * @param second the second.
 908:    */
 909:   public final void set(int year, int month, int date, int hour, int minute,
 910:                         int second)
 911:   {
 912:     set(year, month, date, hour, minute);
 913:     fields[SECOND] = second;
 914:     isSet[SECOND] = true;
 915:   }
 916: 
 917:   /**
 918:    * Clears the values of all the time fields.
 919:    */
 920:   public final void clear()
 921:   {
 922:     isTimeSet = false;
 923:     areFieldsSet = false;
 924:     int zoneOffs = zone.getRawOffset();
 925:     int[] tempFields = 
 926:                        {
 927:                          1, 1970, JANUARY, 1, 1, 1, 1, THURSDAY, 1, AM, 0, 0, 0,
 928:                          0, 0, zoneOffs, 0
 929:                        };
 930:     fields = tempFields;
 931:     for (int i = 0; i < FIELD_COUNT; i++)
 932:       isSet[i] = false;
 933:   }
 934: 
 935:   /**
 936:    * Clears the values of the specified time field.
 937:    * @param field the time field. One of the time field constants.
 938:    * @throws ArrayIndexOutOfBoundsException if field is outside
 939:    *         the valid range.  The value of field must be >= 0 and
 940:    *         <= <code>FIELD_COUNT</code>.
 941:    */
 942:   public final void clear(int field)
 943:   {
 944:     int[] tempFields = 
 945:                        {
 946:                          1, 1970, JANUARY, 1, 1, 1, 1, THURSDAY, 1, AM, 0, 0, 0,
 947:                          0, 0, zone.getRawOffset(), 0
 948:                        };
 949:     complete();
 950:     isTimeSet = false;
 951:     areFieldsSet = false;
 952:     isSet[field] = false;
 953:     fields[field] = tempFields[field];
 954:   }
 955: 
 956:   /**
 957:    * Determines if the specified field has a valid value.
 958:    * @return true if the specified field has a value.
 959:    * @throws ArrayIndexOutOfBoundsException if the field is outside
 960:    *         the valid range.  The value of field must be >= 0 and
 961:    *         <= <code>FIELD_COUNT</code>.
 962:    */
 963:   public final boolean isSet(int field)
 964:   {
 965:     return isSet[field];
 966:   }
 967: 
 968:   /**
 969:    * Fills any unset fields in the time field list
 970:    */
 971:   protected void complete()
 972:   {
 973:     if (! isTimeSet)
 974:       computeTime();
 975:     if (! areFieldsSet)
 976:       computeFields();
 977:   }
 978: 
 979:   /**
 980:    * Compares the given calendar with this.
 981:    * @param o the object to that we should compare.
 982:    * @return true, if the given object is a calendar, that represents
 983:    * the same time (but doesn't necessary have the same fields).
 984:    */
 985:   public boolean equals(Object o)
 986:   {
 987:     if (! (o instanceof Calendar))
 988:       return false;
 989:     Calendar cal = (Calendar) o;
 990:     if (getTimeInMillis() == ((Calendar) o).getTimeInMillis()
 991:         && cal.getFirstDayOfWeek() == getFirstDayOfWeek()
 992:         && cal.isLenient() == isLenient()
 993:         && cal.getMinimalDaysInFirstWeek() == getMinimalDaysInFirstWeek())
 994:       {
 995:         TimeZone self = getTimeZone();
 996:         TimeZone oth = cal.getTimeZone();
 997:         return self == null ? oth == null : self.equals(oth);
 998:       }
 999:     return false;
1000:   }
1001: 
1002:   /**
1003:    * Returns a hash code for this calendar.
1004:    * @return a hash code, which fullfits the general contract of
1005:    * <code>hashCode()</code>
1006:    */
1007:   public int hashCode()
1008:   {
1009:     long time = getTimeInMillis();
1010:     int val = (int) ((time & 0xffffffffL) ^ (time >> 32));
1011:     val += (getFirstDayOfWeek() + (isLenient() ? 1230 : 1237)
1012:             + getMinimalDaysInFirstWeek());
1013:     TimeZone self = getTimeZone();
1014:     if (self != null)
1015:       val ^= self.hashCode();
1016:     return val;
1017:   }
1018: 
1019:   /**
1020:    * Compares the given calendar with this.
1021:    * @param o the object to that we should compare.
1022:    * @return true, if the given object is a calendar, and this calendar
1023:    * represents a smaller time than the calendar o.
1024:    * @exception ClassCastException if o is not an calendar.
1025:    * @since JDK1.2 you don't need to override this method
1026:    */
1027:   public boolean before(Object o)
1028:   {
1029:     return getTimeInMillis() < ((Calendar) o).getTimeInMillis();
1030:   }
1031: 
1032:   /**
1033:    * Compares the given calendar with this.
1034:    * @param o the object to that we should compare.
1035:    * @return true, if the given object is a calendar, and this calendar
1036:    * represents a bigger time than the calendar o.
1037:    * @exception ClassCastException if o is not an calendar.
1038:    * @since JDK1.2 you don't need to override this method
1039:    */
1040:   public boolean after(Object o)
1041:   {
1042:     return getTimeInMillis() > ((Calendar) o).getTimeInMillis();
1043:   }
1044: 
1045:   /**
1046:    * Adds the specified amount of time to the given time field.  The
1047:    * amount may be negative to subtract the time.  If the field overflows
1048:    * it does what you expect: Jan, 25 + 10 Days is Feb, 4.
1049:    * @param field the time field. One of the time field constants.
1050:    * @param amount the amount of time.
1051:    * @throws ArrayIndexOutOfBoundsException if the field is outside
1052:    *         the valid range.  The value of field must be >= 0 and
1053:    *         <= <code>FIELD_COUNT</code>.
1054:    */
1055:   public abstract void add(int field, int amount);
1056: 
1057:   /**
1058:    * Rolls the specified time field up or down.  This means add one
1059:    * to the specified field, but don't change the other fields.  If
1060:    * the maximum for this field is reached, start over with the
1061:    * minimum value.  <br>
1062:    *
1063:    * <strong>Note:</strong> There may be situation, where the other
1064:    * fields must be changed, e.g rolling the month on May, 31.
1065:    * The date June, 31 is automatically converted to July, 1.
1066:    * @param field the time field. One of the time field constants.
1067:    * @param up the direction, true for up, false for down.
1068:    * @throws ArrayIndexOutOfBoundsException if the field is outside
1069:    *         the valid range.  The value of field must be >= 0 and
1070:    *         <= <code>FIELD_COUNT</code>.
1071:    */
1072:   public abstract void roll(int field, boolean up);
1073: 
1074:   /**
1075:    * Rolls up or down the specified time field by the given amount.
1076:    * A negative amount rolls down.  The default implementation is
1077:    * call <code>roll(int, boolean)</code> for the specified amount.
1078:    *
1079:    * Subclasses should override this method to do more intuitiv things.
1080:    *
1081:    * @param field the time field. One of the time field constants.
1082:    * @param amount the amount to roll by, positive for rolling up,
1083:    * negative for rolling down.
1084:    * @throws ArrayIndexOutOfBoundsException if the field is outside
1085:    *         the valid range.  The value of field must be >= 0 and
1086:    *         <= <code>FIELD_COUNT</code>.
1087:    * @since JDK1.2
1088:    */
1089:   public void roll(int field, int amount)
1090:   {
1091:     while (amount > 0)
1092:       {
1093:     roll(field, true);
1094:     amount--;
1095:       }
1096:     while (amount < 0)
1097:       {
1098:     roll(field, false);
1099:     amount++;
1100:       }
1101:   }
1102: 
1103:   /**
1104:    * Sets the time zone to the specified value.
1105:    * @param zone the new time zone
1106:    */
1107:   public void setTimeZone(TimeZone zone)
1108:   {
1109:     this.zone = zone;
1110:     computeTime();
1111:     computeFields();
1112:   }
1113: 
1114:   /**
1115:    * Gets the time zone of this calendar
1116:    * @return the current time zone.
1117:    */
1118:   public TimeZone getTimeZone()
1119:   {
1120:     return zone;
1121:   }
1122: 
1123:   /**
1124:    * Specifies if the date/time interpretation should be lenient.
1125:    * If the flag is set, a date such as "February 30, 1996" will be
1126:    * treated as the 29th day after the February 1.  If this flag
1127:    * is false, such dates will cause an exception.
1128:    * @param lenient true, if the date should be interpreted linient,
1129:    * false if it should be interpreted strict.
1130:    */
1131:   public void setLenient(boolean lenient)
1132:   {
1133:     this.lenient = lenient;
1134:   }
1135: 
1136:   /**
1137:    * Tells if the date/time interpretation is lenient.
1138:    * @return true, if the date should be interpreted linient,
1139:    * false if it should be interpreted strict.
1140:    */
1141:   public boolean isLenient()
1142:   {
1143:     return lenient;
1144:   }
1145: 
1146:   /**
1147:    * Sets what the first day of week is.  This is used for
1148:    * WEEK_OF_MONTH and WEEK_OF_YEAR fields.
1149:    * @param value the first day of week.  One of SUNDAY to SATURDAY.
1150:    */
1151:   public void setFirstDayOfWeek(int value)
1152:   {
1153:     firstDayOfWeek = value;
1154:   }
1155: 
1156:   /**
1157:    * Gets what the first day of week is.  This is used for
1158:    * WEEK_OF_MONTH and WEEK_OF_YEAR fields.
1159:    * @return the first day of week.  One of SUNDAY to SATURDAY.
1160:    */
1161:   public int getFirstDayOfWeek()
1162:   {
1163:     return firstDayOfWeek;
1164:   }
1165: 
1166:   /**
1167:    * Sets how many days are required in the first week of the year.
1168:    * If the first day of the year should be the first week you should
1169:    * set this value to 1.  If the first week must be a full week, set
1170:    * it to 7.
1171:    * @param value the minimal days required in the first week.
1172:    */
1173:   public void setMinimalDaysInFirstWeek(int value)
1174:   {
1175:     minimalDaysInFirstWeek = value;
1176:   }
1177: 
1178:   /**
1179:    * Gets how many days are required in the first week of the year.
1180:    * @return the minimal days required in the first week.
1181:    * @see #setMinimalDaysInFirstWeek
1182:    */
1183:   public int getMinimalDaysInFirstWeek()
1184:   {
1185:     return minimalDaysInFirstWeek;
1186:   }
1187: 
1188:   /**
1189:    * Gets the smallest value that is allowed for the specified field.
1190:    * @param field the time field. One of the time field constants.
1191:    * @return the smallest value.
1192:    */
1193:   public abstract int getMinimum(int field);
1194: 
1195:   /**
1196:    * Gets the biggest value that is allowed for the specified field.
1197:    * @param field the time field. One of the time field constants.
1198:    * @return the biggest value.
1199:    */
1200:   public abstract int getMaximum(int field);
1201: 
1202:   /**
1203:    * Gets the greatest minimum value that is allowed for the specified field.
1204:    * @param field the time field. One of the time field constants.
1205:    * @return the greatest minimum value.
1206:    */
1207:   public abstract int getGreatestMinimum(int field);
1208: 
1209:   /**
1210:    * Gets the smallest maximum value that is allowed for the
1211:    * specified field.  For example this is 28 for DAY_OF_MONTH.
1212:    * @param field the time field. One of the time field constants.
1213:    * @return the least maximum value.
1214:    */
1215:   public abstract int getLeastMaximum(int field);
1216: 
1217:   /**
1218:    * Gets the actual minimum value that is allowed for the specified field.
1219:    * This value is dependent on the values of the other fields.
1220:    * @param field the time field. One of the time field constants.
1221:    * @return the actual minimum value.
1222:    * @throws ArrayIndexOutOfBoundsException if the field is outside
1223:    *         the valid range.  The value of field must be >= 0 and
1224:    *         <= <code>FIELD_COUNT</code>.
1225:    * @since jdk1.2
1226:    */
1227:   public int getActualMinimum(int field)
1228:   {
1229:     Calendar tmp = (Calendar) clone(); // To avoid restoring state
1230:     int min = tmp.getGreatestMinimum(field);
1231:     int end = tmp.getMinimum(field);
1232:     tmp.set(field, min);
1233:     for (; min > end; min--)
1234:       {
1235:     tmp.add(field, -1); // Try to get smaller
1236:     if (tmp.get(field) != min - 1)
1237:       break; // Done if not successful
1238:       }
1239:     return min;
1240:   }
1241: 
1242:   /**
1243:    * Gets the actual maximum value that is allowed for the specified field.
1244:    * This value is dependent on the values of the other fields.
1245:    * @param field the time field. One of the time field constants.
1246:    * @return the actual maximum value.
1247:    * @throws ArrayIndexOutOfBoundsException if the field is outside
1248:    *         the valid range.  The value of field must be >= 0 and
1249:    *         <= <code>FIELD_COUNT</code>.
1250:    * @since jdk1.2
1251:    */
1252:   public int getActualMaximum(int field)
1253:   {
1254:     Calendar tmp = (Calendar) clone(); // To avoid restoring state
1255:     int max = tmp.getLeastMaximum(field);
1256:     int end = tmp.getMaximum(field);
1257:     tmp.set(field, max);
1258:     for (; max < end; max++)
1259:       {
1260:     tmp.add(field, 1);
1261:     if (tmp.get(field) != max + 1)
1262:       break;
1263:       }
1264:     return max;
1265:   }
1266: 
1267:   /**
1268:    * Compares the time of two calendar instances.
1269:    * @param calendar the calendar to which the time should be compared.
1270:    * @return 0 if the two calendars are set to the same time, 
1271:    * less than 0 if the time of this calendar is before that of 
1272:    * <code>cal</code>, or more than 0 if the time of this calendar is after
1273:    * that of <code>cal</code>.
1274:    *
1275:    * @param cal the calendar to compare this instance with.
1276:    * @throws NullPointerException if <code>cal</code> is null.
1277:    * @throws IllegalArgumentException if either calendar has fields set to 
1278:    * invalid values.
1279:    * @since 1.5
1280:    */
1281:   public int compareTo(Calendar cal)
1282:   {
1283:     long t1 = getTimeInMillis();
1284:     long t2 = cal.getTimeInMillis();
1285:     if(t1 == t2)
1286:       return 0;
1287:     if(t1 > t2)
1288:       return 1;
1289:     return -1;
1290:   }
1291: 
1292:   /**
1293:    * Return a clone of this object.
1294:    */
1295:   public Object clone()
1296:   {
1297:     try
1298:       {
1299:     Calendar cal = (Calendar) super.clone();
1300:     cal.fields = (int[]) fields.clone();
1301:     cal.isSet = (boolean[]) isSet.clone();
1302:     return cal;
1303:       }
1304:     catch (CloneNotSupportedException ex)
1305:       {
1306:     return null;
1307:       }
1308:   }
1309: 
1310:   private static final String[] fieldNames = 
1311:                                              {
1312:                                                ",ERA=", ",YEAR=", ",MONTH=",
1313:                                                ",WEEK_OF_YEAR=",
1314:                                                ",WEEK_OF_MONTH=",
1315:                                                ",DAY_OF_MONTH=",
1316:                                                ",DAY_OF_YEAR=", ",DAY_OF_WEEK=",
1317:                                                ",DAY_OF_WEEK_IN_MONTH=",
1318:                                                ",AM_PM=", ",HOUR=",
1319:                                                ",HOUR_OF_DAY=", ",MINUTE=",
1320:                                                ",SECOND=", ",MILLISECOND=",
1321:                                                ",ZONE_OFFSET=", ",DST_OFFSET="
1322:                                              };
1323: 
1324:   /**
1325:    * Returns a string representation of this object.  It is mainly
1326:    * for debugging purposes and its content is implementation
1327:    * specific.
1328:    */
1329:   public String toString()
1330:   {
1331:     StringBuffer sb = new StringBuffer();
1332:     sb.append(getClass().getName()).append('[');
1333:     sb.append("time=");
1334:     if (isTimeSet)
1335:       sb.append(time);
1336:     else
1337:       sb.append("?");
1338:     sb.append(",zone=" + zone);
1339:     sb.append(",areFieldsSet=" + areFieldsSet);
1340:     for (int i = 0; i < FIELD_COUNT; i++)
1341:       {
1342:     sb.append(fieldNames[i]);
1343:     if (isSet[i])
1344:       sb.append(fields[i]);
1345:     else
1346:       sb.append("?");
1347:       }
1348:     sb.append(",lenient=").append(lenient);
1349:     sb.append(",firstDayOfWeek=").append(firstDayOfWeek);
1350:     sb.append(",minimalDaysInFirstWeek=").append(minimalDaysInFirstWeek);
1351:     sb.append("]");
1352:     return sb.toString();
1353:   }
1354: 
1355:   /**
1356:    * Saves the state of the object to the stream.  Ideally we would
1357:    * only write the time field, but we need to be compatible with
1358:    * earlier versions. <br>
1359:    *
1360:    * This doesn't write the JDK1.1 field nextStamp to the stream, as
1361:    * I don't know what it is good for, and because the documentation
1362:    * says, that it could be omitted.  */
1363:   private void writeObject(ObjectOutputStream stream) throws IOException
1364:   {
1365:     if (! isTimeSet)
1366:       computeTime();
1367:     stream.defaultWriteObject();
1368:   }
1369: 
1370:   /**
1371:    * Reads the object back from stream (deserialization).
1372:    */
1373:   private void readObject(ObjectInputStream stream)
1374:     throws IOException, ClassNotFoundException
1375:   {
1376:     stream.defaultReadObject();
1377:     if (! isTimeSet)
1378:       computeTime();
1379: 
1380:     if (serialVersionOnStream > 1)
1381:       {
1382:     // This is my interpretation of the serial number:
1383:     // Sun wants to remove all fields from the stream someday
1384:     // and will then increase the serialVersion number again.
1385:     // We prepare to be compatible.
1386:     fields = new int[FIELD_COUNT];
1387:     isSet = new boolean[FIELD_COUNT];
1388:     areFieldsSet = false;
1389:       }
1390:   }
1391: 
1392:   /**
1393:    * Returns a localised textual representation of the current value
1394:    * of the given field using the specified style.  If there is no
1395:    * applicable textual representation (e.g. the field has a numeric
1396:    * value), then <code>null</code> is returned.  If one does exist,
1397:    * then the value is obtained from {@link #get(int)} and converted
1398:    * appropriately.  For example, if the <code>MONTH</code> field is
1399:    * requested, then <code>get(MONTH)</code> is called.  This is then
1400:    * converted to a textual representation based on its value and
1401:    * the style requested; if the <code>LONG</code> style is requested
1402:    * and the returned value is <code>11</code> from a
1403:    * {@link GregorianCalendar} implementation, then <code>"December"</code>
1404:    * is returned.  By default, a textual representation is available
1405:    * for all fields which have an applicable value obtainable from
1406:    * {@link java.text.DateFormatSymbols}.
1407:    *
1408:    * @param field the calendar field whose textual representation should
1409:    *              be obtained.
1410:    * @param style the style to use; either {@link #LONG} or {@link #SHORT}.
1411:    * @param locale the locale to use for translation.
1412:    * @return the textual representation of the given field in the specified
1413:    *         style, or <code>null</code> if none is applicable.
1414:    * @throws IllegalArgumentException if <code>field</code> or <code>style</code>
1415:    *                                  or invalid, or the calendar is non-lenient
1416:    *                                  and has invalid values.
1417:    * @throws NullPointerException if <code>locale</code> is <code>null</code>.
1418:    * @since 1.6
1419:    */
1420:   public String getDisplayName(int field, int style, Locale locale)
1421:   {
1422:     if (field < 0 || field >= FIELD_COUNT)
1423:       throw new IllegalArgumentException("The field value, " + field +
1424:                      ", is invalid.");
1425:     if (style != SHORT && style != LONG)
1426:       throw new IllegalArgumentException("The style must be either " +
1427:                      "short or long.");
1428:     if (field == YEAR || field == WEEK_OF_YEAR ||
1429:     field == WEEK_OF_MONTH || field == DAY_OF_MONTH ||
1430:     field == DAY_OF_YEAR || field == DAY_OF_WEEK_IN_MONTH ||
1431:     field == HOUR || field == HOUR_OF_DAY || field == MINUTE ||
1432:     field == SECOND || field == MILLISECOND)
1433:       return null;
1434: 
1435:     int value = get(field);
1436:     DateFormatSymbols syms = DateFormatSymbols.getInstance(locale);
1437:     if (field == ERA)
1438:       return syms.getEras()[value];
1439:     if (field == MONTH)
1440:       if (style == LONG)
1441:     return syms.getMonths()[value];
1442:       else 
1443:     return syms.getShortMonths()[value];
1444:     if (field == DAY_OF_WEEK)
1445:       if (style == LONG)
1446:     return syms.getWeekdays()[value];
1447:       else
1448:     return syms.getShortWeekdays()[value];
1449:     if (field == AM_PM)
1450:       return syms.getAmPmStrings()[value];
1451:     if (field == ZONE_OFFSET)
1452:       if (style == LONG)
1453:     return syms.getZoneStrings()[value][1];
1454:       else
1455:     return syms.getZoneStrings()[value][2];
1456:     if (field == DST_OFFSET)
1457:       if (style == LONG)
1458:     return syms.getZoneStrings()[value][3];
1459:       else
1460:     return syms.getZoneStrings()[value][4];
1461: 
1462:     throw new InternalError("Failed to resolve field " + field +
1463:                 " with style " + style + " for locale " +
1464:                 locale);
1465:   }
1466: 
1467:   /**
1468:    * Returns a map linking all specified textual representations
1469:    * of the given field to their numerical values.  The textual
1470:    * representations included are determined by the specified
1471:    * style and locale.  For example, if the style <code>LONG</code>
1472:    * is specified and the German locale, then the map will
1473:    * contain "Montag" to {@link #MONDAY}, "Dienstag" to
1474:    * {@link #TUESDAY}, "Mittwoch" to {@link #WEDNESDAY} and
1475:    * so on.  The default implementation uses the values returned
1476:    * by {@link DateFormatSymbols} so, for example, the style
1477:    * {@link #ALL_STYLES} and the field {@link #MONTH} will return
1478:    * a map filled with the values returned from
1479:    * {@link DateFormatSymbols#getMonths()} and
1480:    * {@link DateFormatSymbols#getShortMonths()}.  If there are
1481:    * no textual representations for a given field (usually because
1482:    * it is purely numeric, such as the year in the
1483:    * {@link GregorianCalendar}), <code>null</code> is returned.
1484:    *
1485:    * @param field the calendar field whose textual representation should
1486:    *              be obtained.
1487:    * @param style the style to use; either {@link #LONG}, {@link #SHORT}
1488:    *              or {@link ALL_STYLES}.
1489:    * @param locale the locale to use for translation.
1490:    * @return a map of the textual representations of the given field in the
1491:    *         specified style to their numeric values, or <code>null</code>
1492:    *         if none is applicable.
1493:    * @throws IllegalArgumentException if <code>field</code> or <code>style</code>
1494:    *                                  or invalid, or the calendar is non-lenient
1495:    *                                  and has invalid values.
1496:    * @throws NullPointerException if <code>locale</code> is <code>null</code>.
1497:    * @since 1.6
1498:    */
1499:   public Map<String,Integer> getDisplayNames(int field, int style, Locale locale)
1500:   {
1501:     if (field < 0 || field >= FIELD_COUNT)
1502:       throw new IllegalArgumentException("The field value, " + field +
1503:                      ", is invalid.");
1504:     if (style != SHORT && style != LONG && style != ALL_STYLES)
1505:       throw new IllegalArgumentException("The style must be either " +
1506:                      "short, long or all styles.");
1507:     if (field == YEAR || field == WEEK_OF_YEAR ||
1508:     field == WEEK_OF_MONTH || field == DAY_OF_MONTH ||
1509:     field == DAY_OF_YEAR || field == DAY_OF_WEEK_IN_MONTH ||
1510:     field == HOUR || field == HOUR_OF_DAY || field == MINUTE ||
1511:     field == SECOND || field == MILLISECOND)
1512:       return null;
1513: 
1514:     DateFormatSymbols syms = DateFormatSymbols.getInstance(locale);
1515:     Map<String,Integer> map = new HashMap<String,Integer>();
1516:     if (field == ERA)
1517:       {
1518:     String[] eras = syms.getEras();
1519:     for (int a = 0; a < eras.length; ++a)
1520:       map.put(eras[a], a);
1521:     return map;
1522:       }
1523:     if (field == MONTH)
1524:       {
1525:     if (style == LONG || style == ALL_STYLES)
1526:       {
1527:         String[] months = syms.getMonths();
1528:         for (int a = 0; a < months.length; ++a)
1529:           map.put(months[a], a);
1530:       }
1531:     if (style == SHORT || style == ALL_STYLES)
1532:       {
1533:         String[] months = syms.getShortMonths();
1534:         for (int a = 0; a < months.length; ++a)
1535:           map.put(months[a], a);
1536:       }
1537:     return map;
1538:       }
1539:     if (field == DAY_OF_WEEK)
1540:       {
1541:     if (style == LONG || style == ALL_STYLES)
1542:       {
1543:         String[] weekdays = syms.getWeekdays();
1544:         for (int a = SUNDAY; a < weekdays.length; ++a)
1545:           map.put(weekdays[a], a);
1546:       }
1547:     if (style == SHORT || style == ALL_STYLES)
1548:       {
1549:         String[] weekdays = syms.getShortWeekdays();
1550:         for (int a = SUNDAY; a < weekdays.length; ++a)
1551:           map.put(weekdays[a], a);
1552:       }
1553:     return map;
1554:       }
1555:     if (field == AM_PM)
1556:       {
1557:     String[] ampms = syms.getAmPmStrings();
1558:     for (int a = 0; a < ampms.length; ++a)
1559:       map.put(ampms[a], a);
1560:     return map;
1561:       }
1562:     if (field == ZONE_OFFSET)
1563:       {
1564:     String[][] zones = syms.getZoneStrings();
1565:     for (int a = 0; a < zones.length; ++a)
1566:       {
1567:         if (style == LONG || style == ALL_STYLES) 
1568:           map.put(zones[a][1], a);
1569:         if (style == SHORT || style == ALL_STYLES)
1570:           map.put(zones[a][2], a);
1571:       }
1572:     return map;
1573:       }
1574:     if (field == DST_OFFSET)
1575:       {
1576:     String[][] zones = syms.getZoneStrings();
1577:     for (int a = 0; a < zones.length; ++a)
1578:       {
1579:         if (style == LONG || style == ALL_STYLES) 
1580:           map.put(zones[a][3], a);
1581:         if (style == SHORT || style == ALL_STYLES)
1582:           map.put(zones[a][4], a);
1583:       }
1584:     return map;
1585:       }
1586:     
1587:     throw new InternalError("Failed to resolve field " + field +
1588:                 " with style " + style + " for locale " +
1589:                 locale);
1590:   }
1591: 
1592: }