1. /*
  2. * @(#)Calendar.java 1.49 00/01/19
  3. *
  4. * Copyright 1996-2000 Sun Microsystems, Inc. All Rights Reserved.
  5. *
  6. * This software is the proprietary information of Sun Microsystems, Inc.
  7. * Use is subject to license terms.
  8. *
  9. */
  10. /*
  11. * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved
  12. * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
  13. *
  14. * The original version of this source code and documentation is copyrighted
  15. * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  16. * materials are provided under terms of a License Agreement between Taligent
  17. * and Sun. This technology is protected by multiple US and International
  18. * patents. This notice and attribution to Taligent may not be removed.
  19. * Taligent is a registered trademark of Taligent, Inc.
  20. *
  21. */
  22. package java.util;
  23. import java.io.IOException;
  24. import java.io.ObjectInputStream;
  25. import java.io.ObjectOutputStream;
  26. import java.io.Serializable;
  27. import java.text.DateFormat;
  28. /**
  29. * <code>Calendar</code> is an abstract base class for converting between
  30. * a <code>Date</code> object and a set of integer fields such as
  31. * <code>YEAR</code>, <code>MONTH</code>, <code>DAY</code>, <code>HOUR</code>,
  32. * and so on. (A <code>Date</code> object represents a specific instant in
  33. * time with millisecond precision. See
  34. * {@link Date}
  35. * for information about the <code>Date</code> class.)
  36. *
  37. * <p>
  38. * Subclasses of <code>Calendar</code> interpret a <code>Date</code>
  39. * according to the rules of a specific calendar system. The platform
  40. * provides one concrete subclass of <code>Calendar</code>:
  41. * <code>GregorianCalendar</code>. Future subclasses could represent
  42. * the various types of lunar calendars in use in many parts of the world.
  43. *
  44. * <p>
  45. * Like other locale-sensitive classes, <code>Calendar</code> provides a
  46. * class method, <code>getInstance</code>, for getting a generally useful
  47. * object of this type. <code>Calendar</code>'s <code>getInstance</code> method
  48. * returns a <code>GregorianCalendar</code> object whose
  49. * time fields have been initialized with the current date and time:
  50. * <blockquote>
  51. * <pre>
  52. * Calendar rightNow = Calendar.getInstance();
  53. * </pre>
  54. * </blockquote>
  55. *
  56. * <p>A <code>Calendar</code> object can produce all the time field values
  57. * needed to implement the date-time formatting for a particular language and
  58. * calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
  59. * <code>Calendar</code> defines the range of values returned by certain fields,
  60. * as well as their meaning. For example, the first month of the year has value
  61. * <code>MONTH</code> == <code>JANUARY</code> for all calendars. Other values
  62. * are defined by the concrete subclass, such as <code>ERA</code> and
  63. * <code>YEAR</code>. See individual field documentation and subclass
  64. * documentation for details.
  65. *
  66. * <p>When a <code>Calendar</code> is <em>lenient</em>, it accepts a wider range
  67. * of field values than it produces. For example, a lenient
  68. * <code>GregorianCalendar</code> interprets <code>MONTH</code> ==
  69. * <code>JANUARY</code>, <code>DAY_OF_MONTH</code> == 32 as February 1. A
  70. * non-lenient <code>GregorianCalendar</code> throws an exception when given
  71. * out-of-range field settings. When calendars recompute field values for
  72. * return by <code>get()</code>, they normalize them. For example, a
  73. * <code>GregorianCalendar</code> always produces <code>DAY_OF_MONTH</code>
  74. * values between 1 and the length of the month.
  75. *
  76. * <p><code>Calendar</code> defines a locale-specific seven day week using two
  77. * parameters: the first day of the week and the minimal days in first week
  78. * (from 1 to 7). These numbers are taken from the locale resource data when a
  79. * <code>Calendar</code> is constructed. They may also be specified explicitly
  80. * through the API.
  81. *
  82. * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or
  83. * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the
  84. * first week of the month or year as a reference point. The first week of a
  85. * month or year is defined as the earliest seven day period beginning on
  86. * <code>getFirstDayOfWeek()</code> and containing at least
  87. * <code>getMinimalDaysInFirstWeek()</code> days of that month or year. Weeks
  88. * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow
  89. * it. Note that the normalized numbering returned by <code>get()</code> may be
  90. * different. For example, a specific <code>Calendar</code> subclass may
  91. * designate the week before week 1 of a year as week <em>n</em> of the previous
  92. * year.
  93. *
  94. * <p> When computing a <code>Date</code> from time fields, two special
  95. * circumstances may arise: there may be insufficient information to compute the
  96. * <code>Date</code> (such as only year and month but no day in the month), or
  97. * there may be inconsistent information (such as "Tuesday, July 15, 1996" --
  98. * July 15, 1996 is actually a Monday).
  99. *
  100. * <p>
  101. * <strong>Insufficient information.</strong> The calendar will use default
  102. * information to specify the missing fields. This may vary by calendar; for
  103. * the Gregorian calendar, the default for a field is the same as that of the
  104. * start of the epoch: i.e., YEAR = 1970, MONTH = JANUARY, DATE = 1, etc.
  105. *
  106. * <p>
  107. * <strong>Inconsistent information.</strong> If fields conflict, the calendar
  108. * will give preference to fields set more recently. For example, when
  109. * determining the day, the calendar will look for one of the following
  110. * combinations of fields. The most recent combination, as determined by the
  111. * most recently set single field, will be used.
  112. *
  113. * <blockquote>
  114. * <pre>
  115. * MONTH + DAY_OF_MONTH
  116. * MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
  117. * MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
  118. * DAY_OF_YEAR
  119. * DAY_OF_WEEK + WEEK_OF_YEAR
  120. * </pre>
  121. * </blockquote>
  122. *
  123. * For the time of day:
  124. *
  125. * <blockquote>
  126. * <pre>
  127. * HOUR_OF_DAY
  128. * AM_PM + HOUR
  129. * </pre>
  130. * </blockquote>
  131. *
  132. * <p>
  133. * <strong>Note:</strong> for some non-Gregorian calendars, different
  134. * fields may be necessary for complete disambiguation. For example, a full
  135. * specification of the historial Arabic astronomical calendar requires year,
  136. * month, day-of-month <em>and</em> day-of-week in some cases.
  137. *
  138. * <p>
  139. * <strong>Note:</strong> There are certain possible ambiguities in
  140. * interpretation of certain singular times, which are resolved in the
  141. * following ways:
  142. * <ol>
  143. * <li> 24:00:00 "belongs" to the following day. That is,
  144. * 23:59 on Dec 31, 1969 < 24:00 on Jan 1, 1970 < 24:01:00 on Jan 1, 1970
  145. *
  146. * <li> Although historically not precise, midnight also belongs to "am",
  147. * and noon belongs to "pm", so on the same day,
  148. * 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm
  149. * </ol>
  150. *
  151. * <p>
  152. * The date or time format strings are not part of the definition of a
  153. * calendar, as those must be modifiable or overridable by the user at
  154. * runtime. Use {@link DateFormat}
  155. * to format dates.
  156. *
  157. * <p><strong>Field manipulation methods</strong></p>
  158. *
  159. * <p><code>Calendar</code> fields can be changed using three methods:
  160. * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.</p>
  161. *
  162. * <p><strong><code>set(f, value)</code></strong> changes field
  163. * <code>f</code> to <code>value</code>. In addition, it sets an
  164. * internal member variable to indicate that field <code>f</code> has
  165. * been changed. Although field <code>f</code> is changed immediately,
  166. * the calendar's milliseconds is not recomputed until the next call to
  167. * <code>get()</code>, <code>getTime()</code>, or
  168. * <code>getTimeInMillis()</code> is made. Thus, multiple calls to
  169. * <code>set()</code> do not trigger multiple, unnecessary
  170. * computations. As a result of changing a field using
  171. * <code>set()</code>, other fields may also change, depending on the
  172. * field, the field value, and the calendar system. In addition,
  173. * <code>get(f)</code> will not necessarily return <code>value</code>
  174. * after the fields have been recomputed. The specifics are determined by
  175. * the concrete calendar class.</p>
  176. *
  177. * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
  178. * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH,
  179. * Calendar.SEPTEMBER)</code> sets the calendar to September 31,
  180. * 1999. This is a temporary internal representation that resolves to
  181. * October 1, 1999 if <code>getTime()</code>is then called. However, a
  182. * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to
  183. * <code>getTime()</code> sets the calendar to September 30, 1999, since
  184. * no recomputation occurs after <code>set()</code> itself.</p>
  185. *
  186. * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code>
  187. * to field <code>f</code>. This is equivalent to calling <code>set(f,
  188. * get(f) + delta)</code> with two adjustments:</p>
  189. *
  190. * <blockquote>
  191. * <p><strong>Add rule 1</strong>. The value of field <code>f</code>
  192. * after the call minus the value of field <code>f</code> before the
  193. * call is <code>delta</code>, modulo any overflow that has occurred in
  194. * field <code>f</code>. Overflow occurs when a field value exceeds its
  195. * range and, as a result, the next larger field is incremented or
  196. * decremented and the field value is adjusted back into its range.</p>
  197. *
  198. * <p><strong>Add rule 2</strong>. If a smaller field is expected to be
  199. * invariant, but   it is impossible for it to be equal to its
  200. * prior value because of changes in its minimum or maximum after field
  201. * <code>f</code> is changed, then its value is adjusted to be as close
  202. * as possible to its expected value. A smaller field represents a
  203. * smaller unit of time. <code>HOUR</code> is a smaller field than
  204. * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
  205. * that are not expected to be invariant. The calendar system
  206. * determines what fields are expected to be invariant.</p>
  207. * </blockquote>
  208. *
  209. * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces
  210. * an immediate recomputation of the calendar's milliseconds and all
  211. * fields.</p>
  212. *
  213. * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
  214. * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH,
  215. * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule
  216. * 1</strong> sets the <code>MONTH</code> field to September, since
  217. * adding 13 months to August gives September of the next year. Since
  218. * <code>DAY_OF_MONTH</code> cannot be 31 in September in a
  219. * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the
  220. * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although
  221. * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by
  222. * rule 2, since it is expected to change when the month changes in a
  223. * <code>GregorianCalendar</code>.</p>
  224. *
  225. * <p><strong><code>roll(f, delta)</code></strong> adds
  226. * <code>delta</code> to field <code>f</code> without changing larger
  227. * fields. This is equivalent to calling <code>add(f, delta)</code> with
  228. * the following adjustment:</p>
  229. *
  230. * <blockquote>
  231. * <p><strong>Roll rule</strong>. Larger fields are unchanged after the
  232. * call. A larger field represents a larger unit of
  233. * time. <code>DAY_OF_MONTH</code> is a larger field than
  234. * <code>HOUR</code>.</p>
  235. * </blockquote>
  236. *
  237. * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
  238. * originally set to August 31, 1999. Calling <code>roll(Calendar.MONTH,
  239. * 8)</code> sets the calendar to April 30, <strong>1999</strong>. Add
  240. * rule 1 sets the <code>MONTH</code> field to April. Using a
  241. * <code>GregorianCalendar</code>, the <code>DAY_OF_MONTH</code> cannot
  242. * be 31 in the month April. Add rule 2 sets it to the closest possible
  243. * value, 30. Finally, the <strong>roll rule</strong> maintains the
  244. * <code>YEAR</code> field value of 1999.</p>
  245. *
  246. * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
  247. * originally set to Sunday June 6, 1999. Calling
  248. * <code>roll(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to
  249. * Tuesday June 1, 1999, whereas calling
  250. * <code>add(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to
  251. * Sunday May 30, 1999. This is because the roll rule imposes an
  252. * additional constraint: The <code>MONTH</code> must not change when the
  253. * <code>WEEK_OF_MONTH</code> is rolled. Taken together with add rule 1,
  254. * the resultant date must be between Tuesday June 1 and Saturday June
  255. * 5. According to add rule 2, the <code>DAY_OF_WEEK</code>, an invariant
  256. * when changing the <code>WEEK_OF_MONTH</code>, is set to Tuesday, the
  257. * closest possible value to Sunday (where Sunday is the first day of the
  258. * week).</p>
  259. *
  260. * <p><strong>Usage model</strong>. To motivate the behavior of
  261. * <code>add()</code> and <code>roll()</code>, consider a user interface
  262. * component with increment and decrement buttons for the month, day, and
  263. * year, and an underlying <code>GregorianCalendar</code>. If the
  264. * interface reads January 31, 1999 and the user presses the month
  265. * increment button, what should it read? If the underlying
  266. * implementation uses <code>set()</code>, it might read March 3, 1999. A
  267. * better result would be February 28, 1999. Furthermore, if the user
  268. * presses the month increment button again, it should read March 31,
  269. * 1999, not March 28, 1999. By saving the original date and using either
  270. * <code>add()</code> or <code>roll()</code>, depending on whether larger
  271. * fields should be affected, the user interface can behave as most users
  272. * will intuitively expect.</p>
  273. *
  274. * @see Date
  275. * @see GregorianCalendar
  276. * @see TimeZone
  277. * @see java.text.DateFormat
  278. * @version 1.49, 01/19/00
  279. * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
  280. * @since JDK1.1
  281. */
  282. public abstract class Calendar implements Serializable, Cloneable {
  283. // Data flow in Calendar
  284. // ---------------------
  285. // The current time is represented in two ways by Calendar: as UTC
  286. // milliseconds from the epoch start (1 January 1970 0:00 UTC), and as local
  287. // fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the
  288. // millis from the fields, and vice versa. The data needed to do this
  289. // conversion is encapsulated by a TimeZone object owned by the Calendar.
  290. // The data provided by the TimeZone object may also be overridden if the
  291. // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
  292. // keeps track of what information was most recently set by the caller, and
  293. // uses that to compute any other information as needed.
  294. // If the user sets the fields using set(), the data flow is as follows.
  295. // This is implemented by the Calendar subclass's computeTime() method.
  296. // During this process, certain fields may be ignored. The disambiguation
  297. // algorithm for resolving which fields to pay attention to is described
  298. // above.
  299. // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
  300. // |
  301. // | Using Calendar-specific algorithm
  302. // V
  303. // local standard millis
  304. // |
  305. // | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
  306. // V
  307. // UTC millis (in time data member)
  308. // If the user sets the UTC millis using setTime(), the data flow is as
  309. // follows. This is implemented by the Calendar subclass's computeFields()
  310. // method.
  311. // UTC millis (in time data member)
  312. // |
  313. // | Using TimeZone getOffset()
  314. // V
  315. // local standard millis
  316. // |
  317. // | Using Calendar-specific algorithm
  318. // V
  319. // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
  320. // In general, a round trip from fields, through local and UTC millis, and
  321. // back out to fields is made when necessary. This is implemented by the
  322. // complete() method. Resolving a partial set of fields into a UTC millis
  323. // value allows all remaining fields to be generated from that value. If
  324. // the Calendar is lenient, the fields are also renormalized to standard
  325. // ranges when they are regenerated.
  326. /**
  327. * Field number for <code>get</code> and <code>set</code> indicating the
  328. * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific
  329. * value; see subclass documentation.
  330. * @see GregorianCalendar#AD
  331. * @see GregorianCalendar#BC
  332. */
  333. public final static int ERA = 0;
  334. /**
  335. * Field number for <code>get</code> and <code>set</code> indicating the
  336. * year. This is a calendar-specific value; see subclass documentation.
  337. */
  338. public final static int YEAR = 1;
  339. /**
  340. * Field number for <code>get</code> and <code>set</code> indicating the
  341. * month. This is a calendar-specific value. The first month of the year is
  342. * <code>JANUARY</code> the last depends on the number of months in a year.
  343. * @see #JANUARY
  344. * @see #FEBRUARY
  345. * @see #MARCH
  346. * @see #APRIL
  347. * @see #MAY
  348. * @see #JUNE
  349. * @see #JULY
  350. * @see #AUGUST
  351. * @see #SEPTEMBER
  352. * @see #OCTOBER
  353. * @see #NOVEMBER
  354. * @see #DECEMBER
  355. * @see #UNDECIMBER
  356. */
  357. public final static int MONTH = 2;
  358. /**
  359. * Field number for <code>get</code> and <code>set</code> indicating the
  360. * week number within the current year. The first week of the year, as
  361. * defined by <code>getFirstDayOfWeek()</code> and
  362. * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define
  363. * the value of <code>WEEK_OF_YEAR</code> for days before the first week of
  364. * the year.
  365. * @see #getFirstDayOfWeek
  366. * @see #getMinimalDaysInFirstWeek
  367. */
  368. public final static int WEEK_OF_YEAR = 3;
  369. /**
  370. * Field number for <code>get</code> and <code>set</code> indicating the
  371. * week number within the current month. The first week of the month, as
  372. * defined by <code>getFirstDayOfWeek()</code> and
  373. * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define
  374. * the value of <code>WEEK_OF_MONTH</code> for days before the first week of
  375. * the month.
  376. * @see #getFirstDayOfWeek
  377. * @see #getMinimalDaysInFirstWeek
  378. */
  379. public final static int WEEK_OF_MONTH = 4;
  380. /**
  381. * Field number for <code>get</code> and <code>set</code> indicating the
  382. * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
  383. * The first day of the month has value 1.
  384. * @see #DAY_OF_MONTH
  385. */
  386. public final static int DATE = 5;
  387. /**
  388. * Field number for <code>get</code> and <code>set</code> indicating the
  389. * day of the month. This is a synonym for <code>DATE</code>.
  390. * The first day of the month has value 1.
  391. * @see #DATE
  392. */
  393. public final static int DAY_OF_MONTH = 5;
  394. /**
  395. * Field number for <code>get</code> and <code>set</code> indicating the day
  396. * number within the current year. The first day of the year has value 1.
  397. */
  398. public final static int DAY_OF_YEAR = 6;
  399. /**
  400. * Field number for <code>get</code> and <code>set</code> indicating the day
  401. * of the week. This field takes values <code>SUNDAY</code>,
  402. * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
  403. * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
  404. * @see #SUNDAY
  405. * @see #MONDAY
  406. * @see #TUESDAY
  407. * @see #WEDNESDAY
  408. * @see #THURSDAY
  409. * @see #FRIDAY
  410. * @see #SATURDAY
  411. */
  412. public final static int DAY_OF_WEEK = 7;
  413. /**
  414. * Field number for <code>get</code> and <code>set</code> indicating the
  415. * ordinal number of the day of the week within the current month. Together
  416. * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
  417. * within a month. Unlike <code>WEEK_OF_MONTH</code> and
  418. * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
  419. * <code>getFirstDayOfWeek()</code> or
  420. * <code>getMinimalDaysInFirstWeek()</code>. <code>DAY_OF_MONTH 1</code>
  421. * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
  422. * 1</code> <code>8</code> through <code>15</code> correspond to
  423. * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
  424. * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
  425. * <code>DAY_OF_WEEK_IN_MONTH 1</code>. Negative values count back from the
  426. * end of the month, so the last Sunday of a month is specified as
  427. * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>. Because
  428. * negative values count backward they will usually be aligned differently
  429. * within the month than positive values. For example, if a month has 31
  430. * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
  431. * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
  432. * @see #DAY_OF_WEEK
  433. * @see #WEEK_OF_MONTH
  434. */
  435. public final static int DAY_OF_WEEK_IN_MONTH = 8;
  436. /**
  437. * Field number for <code>get</code> and <code>set</code> indicating
  438. * whether the <code>HOUR</code> is before or after noon.
  439. * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
  440. * @see #AM
  441. * @see #PM
  442. * @see #HOUR
  443. */
  444. public final static int AM_PM = 9;
  445. /**
  446. * Field number for <code>get</code> and <code>set</code> indicating the
  447. * hour of the morning or afternoon. <code>HOUR</code> is used for the 12-hour
  448. * clock.
  449. * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
  450. * @see #AM_PM
  451. * @see #HOUR_OF_DAY
  452. */
  453. public final static int HOUR = 10;
  454. /**
  455. * Field number for <code>get</code> and <code>set</code> indicating the
  456. * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
  457. * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
  458. * @see #HOUR
  459. */
  460. public final static int HOUR_OF_DAY = 11;
  461. /**
  462. * Field number for <code>get</code> and <code>set</code> indicating the
  463. * minute within the hour.
  464. * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4.
  465. */
  466. public final static int MINUTE = 12;
  467. /**
  468. * Field number for <code>get</code> and <code>set</code> indicating the
  469. * second within the minute.
  470. * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15.
  471. */
  472. public final static int SECOND = 13;
  473. /**
  474. * Field number for <code>get</code> and <code>set</code> indicating the
  475. * millisecond within the second.
  476. * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250.
  477. */
  478. public final static int MILLISECOND = 14;
  479. /**
  480. * Field number for <code>get</code> and <code>set</code> indicating the
  481. * raw offset from GMT in milliseconds.
  482. */
  483. public final static int ZONE_OFFSET = 15;
  484. /**
  485. * Field number for <code>get</code> and <code>set</code> indicating the
  486. * daylight savings offset in milliseconds.
  487. */
  488. public final static int DST_OFFSET = 16;
  489. /**
  490. * The number of distict fields recognized by <code>get</code> and <code>set</code>.
  491. * Field numbers range from <code>0..FIELD_COUNT-1</code>.
  492. */
  493. public final static int FIELD_COUNT = 17;
  494. /**
  495. * Value of the <code>DAY_OF_WEEK</code> field indicating
  496. * Sunday.
  497. */
  498. public final static int SUNDAY = 1;
  499. /**
  500. * Value of the <code>DAY_OF_WEEK</code> field indicating
  501. * Monday.
  502. */
  503. public final static int MONDAY = 2;
  504. /**
  505. * Value of the <code>DAY_OF_WEEK</code> field indicating
  506. * Tuesday.
  507. */
  508. public final static int TUESDAY = 3;
  509. /**
  510. * Value of the <code>DAY_OF_WEEK</code> field indicating
  511. * Wednesday.
  512. */
  513. public final static int WEDNESDAY = 4;
  514. /**
  515. * Value of the <code>DAY_OF_WEEK</code> field indicating
  516. * Thursday.
  517. */
  518. public final static int THURSDAY = 5;
  519. /**
  520. * Value of the <code>DAY_OF_WEEK</code> field indicating
  521. * Friday.
  522. */
  523. public final static int FRIDAY = 6;
  524. /**
  525. * Value of the <code>DAY_OF_WEEK</code> field indicating
  526. * Saturday.
  527. */
  528. public final static int SATURDAY = 7;
  529. /**
  530. * Value of the <code>MONTH</code> field indicating the
  531. * first month of the year.
  532. */
  533. public final static int JANUARY = 0;
  534. /**
  535. * Value of the <code>MONTH</code> field indicating the
  536. * second month of the year.
  537. */
  538. public final static int FEBRUARY = 1;
  539. /**
  540. * Value of the <code>MONTH</code> field indicating the
  541. * third month of the year.
  542. */
  543. public final static int MARCH = 2;
  544. /**
  545. * Value of the <code>MONTH</code> field indicating the
  546. * fourth month of the year.
  547. */
  548. public final static int APRIL = 3;
  549. /**
  550. * Value of the <code>MONTH</code> field indicating the
  551. * fifth month of the year.
  552. */
  553. public final static int MAY = 4;
  554. /**
  555. * Value of the <code>MONTH</code> field indicating the
  556. * sixth month of the year.
  557. */
  558. public final static int JUNE = 5;
  559. /**
  560. * Value of the <code>MONTH</code> field indicating the
  561. * seventh month of the year.
  562. */
  563. public final static int JULY = 6;
  564. /**
  565. * Value of the <code>MONTH</code> field indicating the
  566. * eighth month of the year.
  567. */
  568. public final static int AUGUST = 7;
  569. /**
  570. * Value of the <code>MONTH</code> field indicating the
  571. * ninth month of the year.
  572. */
  573. public final static int SEPTEMBER = 8;
  574. /**
  575. * Value of the <code>MONTH</code> field indicating the
  576. * tenth month of the year.
  577. */
  578. public final static int OCTOBER = 9;
  579. /**
  580. * Value of the <code>MONTH</code> field indicating the
  581. * eleventh month of the year.
  582. */
  583. public final static int NOVEMBER = 10;
  584. /**
  585. * Value of the <code>MONTH</code> field indicating the
  586. * twelfth month of the year.
  587. */
  588. public final static int DECEMBER = 11;
  589. /**
  590. * Value of the <code>MONTH</code> field indicating the
  591. * thirteenth month of the year. Although <code>GregorianCalendar</code>
  592. * does not use this value, lunar calendars do.
  593. */
  594. public final static int UNDECIMBER = 12;
  595. /**
  596. * Value of the <code>AM_PM</code> field indicating the
  597. * period of the day from midnight to just before noon.
  598. */
  599. public final static int AM = 0;
  600. /**
  601. * Value of the <code>AM_PM</code> field indicating the
  602. * period of the day from noon to just before midnight.
  603. */
  604. public final static int PM = 1;
  605. // Internal notes:
  606. // Calendar contains two kinds of time representations: current "time" in
  607. // milliseconds, and a set of time "fields" representing the current time.
  608. // The two representations are usually in sync, but can get out of sync
  609. // as follows.
  610. // 1. Initially, no fields are set, and the time is invalid.
  611. // 2. If the time is set, all fields are computed and in sync.
  612. // 3. If a single field is set, the time is invalid.
  613. // Recomputation of the time and fields happens when the object needs
  614. // to return a result to the user, or use a result for a computation.
  615. /**
  616. * The field values for the currently set time for this calendar.
  617. * This is an array of <code>FIELD_COUNT</code> integers, with index values
  618. * <code>ERA</code> through <code>DST_OFFSET</code>.
  619. * @serial
  620. */
  621. protected int fields[]; // NOTE: Make transient when possible
  622. /**
  623. * The flags which tell if a specified time field for the calendar is set.
  624. * A new object has no fields set. After the first call to a method
  625. * which generates the fields, they all remain set after that.
  626. * This is an array of <code>FIELD_COUNT</code> booleans, with index values
  627. * <code>ERA</code> through <code>DST_OFFSET</code>.
  628. * @serial
  629. */
  630. protected boolean isSet[]; // NOTE: Remove when possible
  631. /**
  632. * Pseudo-time-stamps which specify when each field was set. There
  633. * are two special values, UNSET and INTERNALLY_SET. Values from
  634. * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
  635. */
  636. transient int stamp[];
  637. /**
  638. * The currently set time for this calendar, expressed in milliseconds after
  639. * January 1, 1970, 0:00:00 GMT.
  640. * @see #isTimeSet
  641. * @serial
  642. */
  643. protected long time;
  644. /**
  645. * True if then the value of <code>time</code> is valid.
  646. * The time is made invalid by a change to an item of <code>field[]</code>.
  647. * @see #time
  648. * @serial
  649. */
  650. protected boolean isTimeSet; // NOTE: Make transient when possible
  651. /**
  652. * True if <code>fields[]</code> are in sync with the currently set time.
  653. * If false, then the next attempt to get the value of a field will
  654. * force a recomputation of all fields from the current value of
  655. * <code>time</code>.
  656. * @serial
  657. */
  658. protected boolean areFieldsSet; // NOTE: Make transient when possible
  659. /**
  660. * True if all fields have been set.
  661. * @serial
  662. */
  663. transient boolean areAllFieldsSet;
  664. /**
  665. * True if this calendar allows out-of-range field values during computation
  666. * of <code>time</code> from <code>fields[]</code>.
  667. * @see #setLenient
  668. * @serial
  669. */
  670. private boolean lenient = true;
  671. /**
  672. * The <code>TimeZone</code> used by this calendar. </code>Calendar</code>
  673. * uses the time zone data to translate between locale and GMT time.
  674. * @serial
  675. */
  676. private TimeZone zone;
  677. /**
  678. * The first day of the week, with possible values <code>SUNDAY</code>,
  679. * <code>MONDAY</code>, etc. This is a locale-dependent value.
  680. * @serial
  681. */
  682. private int firstDayOfWeek;
  683. /**
  684. * The number of days required for the first week in a month or year,
  685. * with possible values from 1 to 7. This is a locale-dependent value.
  686. * @serial
  687. */
  688. private int minimalDaysInFirstWeek;
  689. /**
  690. * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
  691. * of a Locale.
  692. */
  693. private static Hashtable cachedLocaleData = new Hashtable(3);
  694. // Special values of stamp[]
  695. static final int UNSET = 0;
  696. static final int INTERNALLY_SET = 1;
  697. static final int MINIMUM_USER_STAMP = 2;
  698. /**
  699. * The next available value for <code>stamp[]</code>, an internal array.
  700. * This actually should not be written out to the stream, and will probably
  701. * be removed from the stream in the near future. In the meantime,
  702. * a value of <code>MINIMUM_USER_STAMP</code> should be used.
  703. * @serial
  704. */
  705. private int nextStamp = MINIMUM_USER_STAMP;
  706. // the internal serial version which says which version was written
  707. // - 0 (default) for version up to JDK 1.1.5
  708. // - 1 for version from JDK 1.1.6, which writes a correct 'time' value
  709. // as well as compatible values for other fields. This is a
  710. // transitional format.
  711. // - 2 (not implemented yet) a future version, in which fields[],
  712. // areFieldsSet, and isTimeSet become transient, and isSet[] is
  713. // removed. In JDK 1.1.6 we write a format compatible with version 2.
  714. static final int currentSerialVersion = 1;
  715. /**
  716. * The version of the serialized data on the stream. Possible values:
  717. * <dl>
  718. * <dt><b>0</b> or not present on stream</dt>
  719. * <dd>
  720. * JDK 1.1.5 or earlier.
  721. * </dd>
  722. * <dt><b>1</b></dt>
  723. * <dd>
  724. * JDK 1.1.6 or later. Writes a correct 'time' value
  725. * as well as compatible values for other fields. This is a
  726. * transitional format.
  727. * </dd>
  728. * </dl>
  729. * When streaming out this class, the most recent format
  730. * and the highest allowable <code>serialVersionOnStream</code>
  731. * is written.
  732. * @serial
  733. * @since JDK1.1.6
  734. */
  735. private int serialVersionOnStream = currentSerialVersion;
  736. // Proclaim serialization compatibility with JDK 1.1
  737. static final long serialVersionUID = -1807547505821590642L;
  738. /**
  739. * Constructs a Calendar with the default time zone
  740. * and locale.
  741. * @see TimeZone#getDefault
  742. */
  743. protected Calendar()
  744. {
  745. this(TimeZone.getDefault(), Locale.getDefault());
  746. }
  747. /**
  748. * Constructs a calendar with the specified time zone and locale.
  749. * @param zone the time zone to use
  750. * @param aLocale the locale for the week data
  751. */
  752. protected Calendar(TimeZone zone, Locale aLocale)
  753. {
  754. fields = new int[FIELD_COUNT];
  755. isSet = new boolean[FIELD_COUNT];
  756. stamp = new int[FIELD_COUNT];
  757. this.zone = zone;
  758. setWeekCountData(aLocale);
  759. }
  760. /**
  761. * Gets a calendar using the default time zone and locale.
  762. * @return a Calendar.
  763. */
  764. public static synchronized Calendar getInstance()
  765. {
  766. return new GregorianCalendar();
  767. }
  768. /**
  769. * Gets a calendar using the specified time zone and default locale.
  770. * @param zone the time zone to use
  771. * @return a Calendar.
  772. */
  773. public static synchronized Calendar getInstance(TimeZone zone)
  774. {
  775. return new GregorianCalendar(zone, Locale.getDefault());
  776. }
  777. /**
  778. * Gets a calendar using the default time zone and specified locale.
  779. * @param aLocale the locale for the week data
  780. * @return a Calendar.
  781. */
  782. public static synchronized Calendar getInstance(Locale aLocale)
  783. {
  784. return new GregorianCalendar(TimeZone.getDefault(), aLocale);
  785. }
  786. /**
  787. * Gets a calendar with the specified time zone and locale.
  788. * @param zone the time zone to use
  789. * @param aLocale the locale for the week data
  790. * @return a Calendar.
  791. */
  792. public static synchronized Calendar getInstance(TimeZone zone,
  793. Locale aLocale)
  794. {
  795. return new GregorianCalendar(zone, aLocale);
  796. }
  797. /**
  798. * Gets the list of locales for which Calendars are installed.
  799. * @return the list of locales for which Calendars are installed.
  800. */
  801. public static synchronized Locale[] getAvailableLocales()
  802. {
  803. return DateFormat.getAvailableLocales();
  804. }
  805. /**
  806. * Converts the current field values in <code>fields[]</code>
  807. * to the millisecond time value
  808. * <code>time</code>.
  809. */
  810. protected abstract void computeTime();
  811. /**
  812. * Converts
  813. * the current millisecond time value
  814. * <code>time</code>
  815. * to field values in <code>fields[]</code>.
  816. * This allows you to sync up the time field values with
  817. * a new time that is set for the calendar. The time is <em>not</em>
  818. * recomputed first; to recompute the time, then the fields, call the
  819. * <code>complete</code> method.
  820. * @see #complete
  821. */
  822. protected abstract void computeFields();
  823. /**
  824. * Gets this Calendar's current time.
  825. * @return the current time.
  826. */
  827. public final Date getTime() {
  828. return new Date( getTimeInMillis() );
  829. }
  830. /**
  831. * Sets this Calendar's current time with the given Date.
  832. * <p>
  833. * Note: Calling <code>setTime()</code> with
  834. * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
  835. * may yield incorrect field values from <code>get()</code>.
  836. * @param date the given Date. */
  837. public final void setTime(Date date) {
  838. setTimeInMillis( date.getTime() );
  839. }
  840. /**
  841. * Gets this Calendar's current time as a long.
  842. * @return the current time as UTC milliseconds from the epoch.
  843. */
  844. protected long getTimeInMillis() {
  845. if (!isTimeSet) updateTime();
  846. return time;
  847. }
  848. /**
  849. * Sets this Calendar's current time from the given long value.
  850. * @param date the new time in UTC milliseconds from the epoch.
  851. */
  852. protected void setTimeInMillis( long millis ) {
  853. isTimeSet = true;
  854. time = millis;
  855. areFieldsSet = false;
  856. if (!areFieldsSet) {
  857. computeFields();
  858. areFieldsSet = true;
  859. areAllFieldsSet = true;
  860. }
  861. }
  862. /**
  863. * Gets the value for a given time field.
  864. * @param field the given time field.
  865. * @return the value for the given time field.
  866. */
  867. public final int get(int field)
  868. {
  869. complete();
  870. return fields[field];
  871. }
  872. /**
  873. * Gets the value for a given time field. This is an internal
  874. * fast time field value getter for the subclasses.
  875. * @param field the given time field.
  876. * @return the value for the given time field.
  877. */
  878. protected final int internalGet(int field)
  879. {
  880. return fields[field];
  881. }
  882. /**
  883. * Sets the value for the given time field. This is an internal
  884. * fast setter for subclasses. It does not affect the areFieldsSet, isTimeSet,
  885. * or areAllFieldsSet flags.
  886. */
  887. final void internalSet(int field, int value)
  888. {
  889. fields[field] = value;
  890. }
  891. /**
  892. * Sets the time field with the given value.
  893. * @param field the given time field.
  894. * @param value the value to be set for the given time field.
  895. */
  896. public final void set(int field, int value)
  897. {
  898. isTimeSet = false;
  899. fields[field] = value;
  900. stamp[field] = nextStamp++;
  901. areFieldsSet = false;
  902. isSet[field] = true; // Remove later
  903. }
  904. /**
  905. * Sets the values for the fields year, month, and date.
  906. * Previous values of other fields are retained. If this is not desired,
  907. * call <code>clear</code> first.
  908. * @param year the value used to set the YEAR time field.
  909. * @param month the value used to set the MONTH time field.
  910. * Month value is 0-based. e.g., 0 for January.
  911. * @param date the value used to set the DATE time field.
  912. */
  913. public final void set(int year, int month, int date)
  914. {
  915. set(YEAR, year);
  916. set(MONTH, month);
  917. set(DATE, date);
  918. }
  919. /**
  920. * Sets the values for the fields year, month, date, hour, and minute.
  921. * Previous values of other fields are retained. If this is not desired,
  922. * call <code>clear</code> first.
  923. * @param year the value used to set the YEAR time field.
  924. * @param month the value used to set the MONTH time field.
  925. * Month value is 0-based. e.g., 0 for January.
  926. * @param date the value used to set the DATE time field.
  927. * @param hour the value used to set the HOUR_OF_DAY time field.
  928. * @param minute the value used to set the MINUTE time field.
  929. */
  930. public final void set(int year, int month, int date, int hour, int minute)
  931. {
  932. set(YEAR, year);
  933. set(MONTH, month);
  934. set(DATE, date);
  935. set(HOUR_OF_DAY, hour);
  936. set(MINUTE, minute);
  937. }
  938. /**
  939. * Sets the values for the fields year, month, date, hour, minute, and second.
  940. * Previous values of other fields are retained. If this is not desired,
  941. * call <code>clear</code> first.
  942. * @param year the value used to set the YEAR time field.
  943. * @param month the value used to set the MONTH time field.
  944. * Month value is 0-based. e.g., 0 for January.
  945. * @param date the value used to set the DATE time field.
  946. * @param hour the value used to set the HOUR_OF_DAY time field.
  947. * @param minute the value used to set the MINUTE time field.
  948. * @param second the value used to set the SECOND time field.
  949. */
  950. public final void set(int year, int month, int date, int hour, int minute,
  951. int second)
  952. {
  953. set(YEAR, year);
  954. set(MONTH, month);
  955. set(DATE, date);
  956. set(HOUR_OF_DAY, hour);
  957. set(MINUTE, minute);
  958. set(SECOND, second);
  959. }
  960. /**
  961. * Clears the values of all the time fields.
  962. */
  963. public final void clear()
  964. {
  965. fields = new int[FIELD_COUNT];
  966. stamp = new int[FIELD_COUNT];
  967. areFieldsSet = false;
  968. areAllFieldsSet = false;
  969. isSet = new boolean[FIELD_COUNT]; // Remove later
  970. isTimeSet = false;
  971. }
  972. /**
  973. * Clears the value in the given time field.
  974. * @param field the time field to be cleared.
  975. */
  976. public final void clear(int field)
  977. {
  978. fields[field] = 0;
  979. stamp[field] = UNSET;
  980. areFieldsSet = false;
  981. areAllFieldsSet = false;
  982. isSet[field] = false; // Remove later
  983. isTimeSet = false;
  984. }
  985. /**
  986. * Determines if the given time field has a value set.
  987. * @return true if the given time field has a value set; false otherwise.
  988. */
  989. public final boolean isSet(int field)
  990. {
  991. return stamp[field] != UNSET;
  992. // return isSet[field];
  993. }
  994. /**
  995. * Fills in any unset fields in the time field list.
  996. */
  997. protected void complete()
  998. {
  999. if (!isTimeSet) updateTime();
  1000. if (!areFieldsSet) {
  1001. computeFields(); // fills in unset fields
  1002. areFieldsSet = true;
  1003. areAllFieldsSet = true;
  1004. }
  1005. }
  1006. /**
  1007. * Compares this calendar to the specified object.
  1008. * The result is <code>true</code> if and only if the argument is
  1009. * not <code>null</code> and is a <code>Calendar</code> object that
  1010. * represents the same calendar as this object.
  1011. * @param obj the object to compare with.
  1012. * @return <code>true</code> if the objects are the same;
  1013. * <code>false</code> otherwise.
  1014. */
  1015. public boolean equals(Object obj) {
  1016. if (this == obj)
  1017. return true;
  1018. if (!(obj instanceof Calendar))
  1019. return false;
  1020. Calendar that = (Calendar)obj;
  1021. return getTimeInMillis() == that.getTimeInMillis() &&
  1022. lenient == that.lenient &&
  1023. firstDayOfWeek == that.firstDayOfWeek &&
  1024. minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&
  1025. zone.equals(that.zone);
  1026. }
  1027. /**
  1028. * Returns a hash code for this calendar.
  1029. * @return a hash code value for this object.
  1030. * @since 1.2
  1031. */
  1032. public int hashCode() {
  1033. /* Don't include the time because (a) we don't want the hash value to
  1034. * move around just because a calendar is set to different times, and
  1035. * (b) we don't want to trigger a time computation just to get a hash.
  1036. * Note that it is not necessary for unequal objects to always have
  1037. * unequal hashes, but equal objects must have equal hashes. */
  1038. return (lenient ? 1 : 0)
  1039. | (firstDayOfWeek << 1)
  1040. | (minimalDaysInFirstWeek << 4)
  1041. | (zone.hashCode() << 7);
  1042. }
  1043. /**
  1044. * Compares the time field records.
  1045. * Equivalent to comparing result of conversion to UTC.
  1046. * @param when the Calendar to be compared with this Calendar.
  1047. * @return true if the current time of this Calendar is before
  1048. * the time of Calendar when; false otherwise.
  1049. */
  1050. public boolean before(Object when) {
  1051. return when instanceof Calendar &&
  1052. getTimeInMillis() < ((Calendar) when).getTimeInMillis();
  1053. }
  1054. /**
  1055. * Compares the time field records.
  1056. * Equivalent to comparing result of conversion to UTC.
  1057. * @param when the Calendar to be compared with this Calendar.
  1058. * @return true if the current time of this Calendar is after
  1059. * the time of Calendar when; false otherwise.
  1060. */
  1061. public boolean after(Object when) {
  1062. return when instanceof Calendar &&
  1063. getTimeInMillis() > ((Calendar) when).getTimeInMillis();
  1064. }
  1065. /**
  1066. * Date Arithmetic function.
  1067. * Adds the specified (signed) amount of time to the given time field,
  1068. * based on the calendar's rules. For example, to subtract 5 days from
  1069. * the current time of the calendar, you can achieve it by calling:
  1070. * <p>add(Calendar.DATE, -5).
  1071. * @param field the time field.
  1072. * @param amount the amount of date or time to be added to the field.
  1073. */
  1074. abstract public void add(int field, int amount);
  1075. /**
  1076. * Time Field Rolling function.
  1077. * Rolls (up/down) a single unit of time on the given time field. For
  1078. * example, to roll the current date up by one day, you can achieve it
  1079. * by calling:
  1080. * <p>roll(Calendar.DATE, true).
  1081. * When rolling on the year or Calendar.YEAR field, it will roll the year
  1082. * value in the range between 1 and the value returned by calling
  1083. * getMaximum(Calendar.YEAR).
  1084. * When rolling on the month or Calendar.MONTH field, other fields like
  1085. * date might conflict and, need to be changed. For instance,
  1086. * rolling the month on the date 01/31/96 will result in 02/29/96.
  1087. * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
  1088. * roll the hour value in the range between 0 and 23, which is zero-based.
  1089. * @param field the time field.
  1090. * @param up indicates if the value of the specified time field is to be
  1091. * rolled up or rolled down. Use true if rolling up, false otherwise.
  1092. */
  1093. abstract public void roll(int field, boolean up);
  1094. /**
  1095. * Time Field Rolling function.
  1096. * Rolls up or down the specified number of units on the given time field.
  1097. * (A negative roll amount means to roll down.)
  1098. * [NOTE: This default implementation on Calendar just repeatedly calls the
  1099. * version of roll() that takes a boolean and rolls by one unit. This may not
  1100. * always do the right thing. For example, if the DAY_OF_MONTH field is 31,
  1101. * rolling through February will leave it set to 28. The GregorianCalendar
  1102. * version of this function takes care of this problem. Other subclasses
  1103. * should also provide overrides of this function that do the right thing.
  1104. *
  1105. * @since 1.2
  1106. */
  1107. public void roll(int field, int amount)
  1108. {
  1109. while (amount > 0) {
  1110. roll(field, true);
  1111. amount--;
  1112. }
  1113. while (amount < 0) {
  1114. roll(field, false);
  1115. amount++;
  1116. }
  1117. }
  1118. /**
  1119. * Sets the time zone with the given time zone value.
  1120. * @param value the given time zone.
  1121. */
  1122. public void setTimeZone(TimeZone value)
  1123. {
  1124. zone = value;
  1125. /* Recompute the fields from the time using the new zone. This also
  1126. * works if isTimeSet is false (after a call to set()). In that case
  1127. * the time will be computed from the fields using the new zone, then
  1128. * the fields will get recomputed from that. Consider the sequence of
  1129. * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
  1130. * Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More
  1131. * generally, a call to setTimeZone() affects calls to set() BEFORE AND
  1132. * AFTER it up to the next call to complete().
  1133. */
  1134. areFieldsSet = false;
  1135. }
  1136. /**
  1137. * Gets the time zone.
  1138. * @return the time zone object associated with this calendar.
  1139. */
  1140. public TimeZone getTimeZone()
  1141. {
  1142. return zone;
  1143. }
  1144. /**
  1145. * Specify whether or not date/time interpretation is to be lenient. With
  1146. * lenient interpretation, a date such as "February 942, 1996" will be
  1147. * treated as being equivalent to the 941st day after February 1, 1996.
  1148. * With strict interpretation, such dates will cause an exception to be
  1149. * thrown.
  1150. *
  1151. * @see java.text.DateFormat#setLenient
  1152. */
  1153. public void setLenient(boolean lenient)
  1154. {
  1155. this.lenient = lenient;
  1156. }
  1157. /**
  1158. * Tell whether date/time interpretation is to be lenient.
  1159. */
  1160. public boolean isLenient()
  1161. {
  1162. return lenient;
  1163. }
  1164. /**
  1165. * Sets what the first day of the week is; e.g., Sunday in US,
  1166. * Monday in France.
  1167. * @param value the given first day of the week.
  1168. */
  1169. public void setFirstDayOfWeek(int value)
  1170. {
  1171. firstDayOfWeek = value;
  1172. }
  1173. /**
  1174. * Gets what the first day of the week is; e.g., Sunday in US,
  1175. * Monday in France.
  1176. * @return the first day of the week.
  1177. */
  1178. public int getFirstDayOfWeek()
  1179. {
  1180. return firstDayOfWeek;
  1181. }
  1182. /**
  1183. * Sets what the minimal days required in the first week of the year are;
  1184. * For example, if the first week is defined as one that contains the first
  1185. * day of the first month of a year, call the method with value 1. If it
  1186. * must be a full week, use value 7.
  1187. * @param value the given minimal days required in the first week
  1188. * of the year.
  1189. */
  1190. public void setMinimalDaysInFirstWeek(int value)
  1191. {
  1192. minimalDaysInFirstWeek = value;
  1193. }
  1194. /**
  1195. * Gets what the minimal days required in the first week of the year are;
  1196. * e.g., if the first week is defined as one that contains the first day
  1197. * of the first month of a year, getMinimalDaysInFirstWeek returns 1. If
  1198. * the minimal days required must be a full week, getMinimalDaysInFirstWeek
  1199. * returns 7.
  1200. * @return the minimal days required in the first week of the year.
  1201. */
  1202. public int getMinimalDaysInFirstWeek()
  1203. {
  1204. return minimalDaysInFirstWeek;
  1205. }
  1206. /**
  1207. * Gets the minimum value for the given time field.
  1208. * e.g., for Gregorian DAY_OF_MONTH, 1.
  1209. * @param field the given time field.
  1210. * @return the minimum value for the given time field.
  1211. */
  1212. abstract public int getMinimum(int field);
  1213. /**
  1214. * Gets the maximum value for the given time field.
  1215. * e.g. for Gregorian DAY_OF_MONTH, 31.
  1216. * @param field the given time field.
  1217. * @return the maximum value for the given time field.
  1218. */
  1219. abstract public int getMaximum(int field);
  1220. /**
  1221. * Gets the highest minimum value for the given field if varies.
  1222. * Otherwise same as getMinimum(). For Gregorian, no difference.
  1223. * @param field the given time field.
  1224. * @return the highest minimum value for the given time field.
  1225. */
  1226. abstract public int getGreatestMinimum(int field);
  1227. /**
  1228. * Gets the lowest maximum value for the given field if varies.
  1229. * Otherwise same as getMaximum(). e.g., for Gregorian DAY_OF_MONTH, 28.
  1230. * @param field the given time field.
  1231. * @return the lowest maximum value for the given time field.
  1232. */
  1233. abstract public int getLeastMaximum(int field);
  1234. /**
  1235. * Return the minimum value that this field could have, given the current date.
  1236. * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
  1237. *
  1238. * The version of this function on Calendar uses an iterative algorithm to determine the
  1239. * actual minimum value for the field. There is almost always a more efficient way to
  1240. * accomplish this (in most cases, you can simply return getMinimum()). GregorianCalendar
  1241. * overrides this function with a more efficient implementation.
  1242. *
  1243. * @param field the field to determine the minimum of
  1244. * @return the minimum of the given field for the current date of this Calendar
  1245. * @since 1.2
  1246. */
  1247. public int getActualMinimum(int field) {
  1248. int fieldValue = getGreatestMinimum(field);
  1249. int endValue = getMinimum(field);
  1250. // if we know that the minimum value is always the same, just return it
  1251. if (fieldValue == endValue) {
  1252. return fieldValue;
  1253. }
  1254. // clone the calendar so we don't mess with the real one, and set it to
  1255. // accept anything for the field values
  1256. Calendar work = (Calendar)this.clone();
  1257. work.setLenient(true);
  1258. // now try each value from getLeastMaximum() to getMaximum() one by one until
  1259. // we get a value that normalizes to another value. The last value that
  1260. // normalizes to itself is the actual minimum for the current date
  1261. int result = fieldValue;
  1262. do {
  1263. work.set(field, fieldValue);
  1264. if (work.get(field) != fieldValue) {
  1265. break;
  1266. } else {
  1267. result = fieldValue;
  1268. fieldValue--;
  1269. }
  1270. } while (fieldValue >= endValue);
  1271. return result;
  1272. }
  1273. /**
  1274. * Return the maximum value that this field could have, given the current date.
  1275. * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
  1276. * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar,
  1277. * for some years the actual maximum for MONTH is 12, and for others 13.
  1278. *
  1279. * The version of this function on Calendar uses an iterative algorithm to determine the
  1280. * actual maximum value for the field. There is almost always a more efficient way to
  1281. * accomplish this (in most cases, you can simply return getMaximum()). GregorianCalendar
  1282. * overrides this function with a more efficient implementation.
  1283. *
  1284. * @param field the field to determine the maximum of
  1285. * @return the maximum of the given field for the current date of this Calendar
  1286. * @since 1.2
  1287. */
  1288. public int getActualMaximum(int field) {
  1289. int fieldValue = getLeastMaximum(field);
  1290. int endValue = getMaximum(field);
  1291. // if we know that the maximum value is always the same, just return it
  1292. if (fieldValue == endValue) {
  1293. return fieldValue;
  1294. }
  1295. // clone the calendar so we don't mess with the real one, and set it to
  1296. // accept anything for the field values
  1297. Calendar work = (Calendar)this.clone();
  1298. work.setLenient(true);
  1299. // if we're counting weeks, set the day of the week to Sunday. We know the
  1300. // last week of a month or year will contain the first day of the week.
  1301. if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH)
  1302. work.set(DAY_OF_WEEK, firstDayOfWeek);
  1303. // now try each value from getLeastMaximum() to getMaximum() one by one until
  1304. // we get a value that normalizes to another value. The last value that
  1305. // normalizes to itself is the actual maximum for the current date
  1306. int result = fieldValue;
  1307. do {
  1308. work.set(field, fieldValue);
  1309. if (work.get(field) != fieldValue) {
  1310. break;
  1311. } else {
  1312. result = fieldValue;
  1313. fieldValue++;
  1314. }
  1315. } while (fieldValue <= endValue);
  1316. return result;
  1317. }
  1318. /**
  1319. * Overrides Cloneable
  1320. */
  1321. public Object clone()
  1322. {
  1323. try {
  1324. Calendar other = (Calendar) super.clone();
  1325. other.fields = new int[FIELD_COUNT];
  1326. other.isSet = new boolean[FIELD_COUNT];
  1327. other.stamp = new int[FIELD_COUNT];
  1328. System.arraycopy(this.fields, 0, other.fields, 0, FIELD_COUNT);
  1329. System.arraycopy(this.isSet, 0, other.isSet, 0, FIELD_COUNT);
  1330. System.arraycopy(this.stamp, 0, other.stamp, 0, FIELD_COUNT);
  1331. other.zone = (TimeZone) zone.clone();
  1332. return other;
  1333. }
  1334. catch (CloneNotSupportedException e) {
  1335. // this shouldn't happen, since we are Cloneable
  1336. throw new InternalError();
  1337. }
  1338. }
  1339. private static final String[] FIELD_NAME = {
  1340. ",ERA=", ",YEAR=", ",MONTH=", ",WEEK_OF_YEAR=", ",WEEK_OF_MONTH=", ",DAY_OF_MONTH=",
  1341. ",DAY_OF_YEAR=", ",DAY_OF_WEEK=", ",DAY_OF_WEEK_IN_MONTH=", ",AM_PM=", ",HOUR=",
  1342. ",HOUR_OF_DAY=", ",MINUTE=", ",SECOND=", ",MILLISECOND=", ",ZONE_OFFSET=",
  1343. ",DST_OFFSET="
  1344. };
  1345. /**
  1346. * Return a string representation of this calendar. This method
  1347. * is intended to be used only for debugging purposes, and the
  1348. * format of the returned string may vary between implementations.
  1349. * The returned string may be empty but may not be <code>null</code>.
  1350. *
  1351. * @return a string representation of this calendar.
  1352. */
  1353. public String toString() {
  1354. StringBuffer buffer = new StringBuffer();
  1355. buffer.append(getClass().getName());
  1356. buffer.append("[time=");
  1357. buffer.append(isTimeSet ? String.valueOf(time) : "?");
  1358. buffer.append(",areFieldsSet=");
  1359. buffer.append(areFieldsSet);
  1360. buffer.append(",areAllFieldsSet=");
  1361. buffer.append(areAllFieldsSet);
  1362. buffer.append(",lenient=");
  1363. buffer.append(lenient);
  1364. buffer.append(",zone=");
  1365. buffer.append(zone);
  1366. buffer.append(",firstDayOfWeek=");
  1367. buffer.append(firstDayOfWeek);
  1368. buffer.append(",minimalDaysInFirstWeek=");
  1369. buffer.append(minimalDaysInFirstWeek);
  1370. for (int i=0; i<FIELD_COUNT; ++i) {
  1371. buffer.append(FIELD_NAME[i]);
  1372. buffer.append(isSet(i) ? String.valueOf(fields[i]) : "?");
  1373. }
  1374. buffer.append(']');
  1375. return buffer.toString();
  1376. }
  1377. // =======================privates===============================
  1378. /**
  1379. * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
  1380. * They are used to figure out the week count for a specific date for
  1381. * a given locale. These must be set when a Calendar is constructed.
  1382. * @param desiredLocale the given locale.
  1383. */
  1384. private void setWeekCountData(Locale desiredLocale)
  1385. {
  1386. /* try to get the Locale data from the cache */
  1387. int[] data = (int[]) cachedLocaleData.get(desiredLocale);
  1388. if (data == null) { /* cache miss */
  1389. ResourceBundle resource
  1390. = ResourceBundle.getBundle("java.text.resources.LocaleElements",
  1391. desiredLocale);
  1392. String[] dateTimePatterns =
  1393. resource.getStringArray("DateTimeElements");
  1394. data = new int[2];
  1395. data[0] = Integer.parseInt(dateTimePatterns[0]);
  1396. data[1] = Integer.parseInt(dateTimePatterns[1]);
  1397. /* cache update */
  1398. cachedLocaleData.put(desiredLocale, data);
  1399. }
  1400. firstDayOfWeek = data[0];
  1401. minimalDaysInFirstWeek = data[1];
  1402. }
  1403. /**
  1404. * Recompute the time and update the status fields isTimeSet
  1405. * and areFieldsSet. Callers should check isTimeSet and only
  1406. * call this method if isTimeSet is false.
  1407. */
  1408. private void updateTime() {
  1409. computeTime();
  1410. // If we are lenient, we need to recompute the fields to normalize
  1411. // the values. Also, if we haven't set all the fields yet (i.e.,
  1412. // in a newly-created object), we need to fill in the fields. [LIU]
  1413. if (isLenient() || !areAllFieldsSet) areFieldsSet = false;
  1414. isTimeSet = true;
  1415. }
  1416. /**
  1417. * Save the state of this object to a stream (i.e., serialize it).
  1418. *
  1419. * Ideally, <code>Calendar</code> would only write out its state data and
  1420. * the current time, and not write any field data out, such as
  1421. * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
  1422. * and <code>isSet[]</code>. <code>nextStamp</code> also should not be part
  1423. * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
  1424. * shipped. To be compatible with JDK 1.1, we will always have to write out
  1425. * the field values and state flags. However, <code>nextStamp</code> can be
  1426. * removed from the serialization stream; this will probably happen in the
  1427. * near future.
  1428. */
  1429. private void writeObject(ObjectOutputStream stream)
  1430. throws IOException
  1431. {
  1432. // Try to compute the time correctly, for the future (stream
  1433. // version 2) in which we don't write out fields[] or isSet[].
  1434. if (!isTimeSet) {
  1435. try {
  1436. updateTime();
  1437. }
  1438. catch (IllegalArgumentException e) {}
  1439. }
  1440. // Write out the 1.1 FCS object.
  1441. stream.defaultWriteObject();
  1442. }
  1443. /**
  1444. * Reconstitute this object from a stream (i.e., deserialize it).
  1445. */
  1446. private void readObject(ObjectInputStream stream)
  1447. throws IOException, ClassNotFoundException
  1448. {
  1449. stream.defaultReadObject();
  1450. stamp = new int[FIELD_COUNT];
  1451. // Starting with version 2 (not implemented yet), we expect that
  1452. // fields[], isSet[], isTimeSet, and areFieldsSet may not be
  1453. // streamed out anymore. We expect 'time' to be correct.
  1454. if (serialVersionOnStream >= 2)
  1455. {
  1456. isTimeSet = true;
  1457. if (fields == null) fields = new int[FIELD_COUNT];
  1458. if (isSet == null) isSet = new boolean[FIELD_COUNT];
  1459. }
  1460. else if (serialVersionOnStream == 0)
  1461. {
  1462. for (int i=0; i<FIELD_COUNT; ++i)
  1463. stamp[i] = isSet[i] ? INTERNALLY_SET : UNSET;
  1464. }
  1465. serialVersionOnStream = currentSerialVersion;
  1466. }
  1467. }