1. /*
  2. * @(#)GregorianCalendar.java 1.73 03/04/27
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. /*
  8. * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved
  9. * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
  10. *
  11. * The original version of this source code and documentation is copyrighted
  12. * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  13. * materials are provided under terms of a License Agreement between Taligent
  14. * and Sun. This technology is protected by multiple US and International
  15. * patents. This notice and attribution to Taligent may not be removed.
  16. * Taligent is a registered trademark of Taligent, Inc.
  17. *
  18. */
  19. package java.util;
  20. import java.io.IOException;
  21. import java.io.ObjectInputStream;
  22. import sun.util.calendar.ZoneInfo;
  23. /**
  24. * <code>GregorianCalendar</code> is a concrete subclass of
  25. * {@link Calendar}
  26. * and provides the standard calendar used by most of the world.
  27. *
  28. * <p>
  29. * The standard (Gregorian) calendar has 2 eras, BC and AD.
  30. *
  31. * <p>
  32. * This implementation handles a single discontinuity, which corresponds by
  33. * default to the date the Gregorian calendar was instituted (October 15, 1582
  34. * in some countries, later in others). The cutover date may be changed by the
  35. * caller by calling <code>setGregorianChange()</code>.
  36. *
  37. * <p>
  38. * Historically, in those countries which adopted the Gregorian calendar first,
  39. * October 4, 1582 was thus followed by October 15, 1582. This calendar models
  40. * this correctly. Before the Gregorian cutover, <code>GregorianCalendar</code>
  41. * implements the Julian calendar. The only difference between the Gregorian
  42. * and the Julian calendar is the leap year rule. The Julian calendar specifies
  43. * leap years every four years, whereas the Gregorian calendar omits century
  44. * years which are not divisible by 400.
  45. *
  46. * <p>
  47. * <code>GregorianCalendar</code> implements <em>proleptic</em> Gregorian and
  48. * Julian calendars. That is, dates are computed by extrapolating the current
  49. * rules indefinitely far backward and forward in time. As a result,
  50. * <code>GregorianCalendar</code> may be used for all years to generate
  51. * meaningful and consistent results. However, dates obtained using
  52. * <code>GregorianCalendar</code> are historically accurate only from March 1, 4
  53. * AD onward, when modern Julian calendar rules were adopted. Before this date,
  54. * leap year rules were applied irregularly, and before 45 BC the Julian
  55. * calendar did not even exist.
  56. *
  57. * <p>
  58. * Prior to the institution of the Gregorian calendar, New Year's Day was
  59. * March 25. To avoid confusion, this calendar always uses January 1. A manual
  60. * adjustment may be made if desired for dates that are prior to the Gregorian
  61. * changeover and which fall between January 1 and March 24.
  62. *
  63. * <p>Values calculated for the <code>WEEK_OF_YEAR</code> field range from 1 to
  64. * 53. Week 1 for a year is the earliest seven day period starting on
  65. * <code>getFirstDayOfWeek()</code> that contains at least
  66. * <code>getMinimalDaysInFirstWeek()</code> days from that year. It thus
  67. * depends on the values of <code>getMinimalDaysInFirstWeek()</code>,
  68. * <code>getFirstDayOfWeek()</code>, and the day of the week of January 1.
  69. * Weeks between week 1 of one year and week 1 of the following year are
  70. * numbered sequentially from 2 to 52 or 53 (as needed).
  71. * <p>For example, January 1, 1998 was a Thursday. If
  72. * <code>getFirstDayOfWeek()</code> is <code>MONDAY</code> and
  73. * <code>getMinimalDaysInFirstWeek()</code> is 4 (these are the values
  74. * reflecting ISO 8601 and many national standards), then week 1 of 1998 starts
  75. * on December 29, 1997, and ends on January 4, 1998. If, however,
  76. * <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>, then week 1 of 1998
  77. * starts on January 4, 1998, and ends on January 10, 1998; the first three days
  78. * of 1998 then are part of week 53 of 1997.
  79. *
  80. * <p>Values calculated for the <code>WEEK_OF_MONTH</code> field range from 0
  81. * to 6. Week 1 of a month (the days with <code>WEEK_OF_MONTH =
  82. * 1</code>) is the earliest set of at least
  83. * <code>getMinimalDaysInFirstWeek()</code> contiguous days in that month,
  84. * ending on the day before <code>getFirstDayOfWeek()</code>. Unlike
  85. * week 1 of a year, week 1 of a month may be shorter than 7 days, need
  86. * not start on <code>getFirstDayOfWeek()</code>, and will not include days of
  87. * the previous month. Days of a month before week 1 have a
  88. * <code>WEEK_OF_MONTH</code> of 0.
  89. *
  90. * <p>For example, if <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>
  91. * and <code>getMinimalDaysInFirstWeek()</code> is 4, then the first week of
  92. * January 1998 is Sunday, January 4 through Saturday, January 10. These days
  93. * have a <code>WEEK_OF_MONTH</code> of 1. Thursday, January 1 through
  94. * Saturday, January 3 have a <code>WEEK_OF_MONTH</code> of 0. If
  95. * <code>getMinimalDaysInFirstWeek()</code> is changed to 3, then January 1
  96. * through January 3 have a <code>WEEK_OF_MONTH</code> of 1.
  97. *
  98. * <p>
  99. * <strong>Example:</strong>
  100. * <blockquote>
  101. * <pre>
  102. * // get the supported ids for GMT-08:00 (Pacific Standard Time)
  103. * String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
  104. * // if no ids were returned, something is wrong. get out.
  105. * if (ids.length == 0)
  106. * System.exit(0);
  107. *
  108. * // begin output
  109. * System.out.println("Current Time");
  110. *
  111. * // create a Pacific Standard Time time zone
  112. * SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
  113. *
  114. * // set up rules for daylight savings time
  115. * pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
  116. * pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
  117. *
  118. * // create a GregorianCalendar with the Pacific Daylight time zone
  119. * // and the current date and time
  120. * Calendar calendar = new GregorianCalendar(pdt);
  121. * Date trialTime = new Date();
  122. * calendar.setTime(trialTime);
  123. *
  124. * // print out a bunch of interesting things
  125. * System.out.println("ERA: " + calendar.get(Calendar.ERA));
  126. * System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
  127. * System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
  128. * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
  129. * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
  130. * System.out.println("DATE: " + calendar.get(Calendar.DATE));
  131. * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
  132. * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
  133. * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
  134. * System.out.println("DAY_OF_WEEK_IN_MONTH: "
  135. * + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
  136. * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
  137. * System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
  138. * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
  139. * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
  140. * System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
  141. * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
  142. * System.out.println("ZONE_OFFSET: "
  143. * + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
  144. * System.out.println("DST_OFFSET: "
  145. * + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));
  146. * System.out.println("Current Time, with hour reset to 3");
  147. * calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override
  148. * calendar.set(Calendar.HOUR, 3);
  149. * System.out.println("ERA: " + calendar.get(Calendar.ERA));
  150. * System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
  151. * System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
  152. * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
  153. * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
  154. * System.out.println("DATE: " + calendar.get(Calendar.DATE));
  155. * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
  156. * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
  157. * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
  158. * System.out.println("DAY_OF_WEEK_IN_MONTH: "
  159. * + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
  160. * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
  161. * System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
  162. * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
  163. * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
  164. * System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
  165. * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
  166. * System.out.println("ZONE_OFFSET: "
  167. * + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); // in hours
  168. * System.out.println("DST_OFFSET: "
  169. * + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); // in hours
  170. * </pre>
  171. * </blockquote>
  172. *
  173. * @see Calendar
  174. * @see TimeZone
  175. * @version 1.73
  176. * @author David Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu
  177. * @since JDK1.1
  178. */
  179. public class GregorianCalendar extends Calendar {
  180. /*
  181. * Implementation Notes
  182. *
  183. * The Julian day number, as used here, is a modified number which has its
  184. * onset at midnight, rather than noon.
  185. *
  186. * The epoch is the number of days or milliseconds from some defined
  187. * starting point. The epoch for java.util.Date is used here; that is,
  188. * milliseconds from January 1, 1970 (Gregorian), midnight UTC. Other
  189. * epochs which are used are January 1, year 1 (Gregorian), which is day 1
  190. * of the Gregorian calendar, and December 30, year 0 (Gregorian), which is
  191. * day 1 of the Julian calendar.
  192. *
  193. * We implement the proleptic Julian and Gregorian calendars. This means we
  194. * implement the modern definition of the calendar even though the
  195. * historical usage differs. For example, if the Gregorian change is set
  196. * to new Date(Long.MIN_VALUE), we have a pure Gregorian calendar which
  197. * labels dates preceding the invention of the Gregorian calendar in 1582 as
  198. * if the calendar existed then.
  199. *
  200. * Likewise, with the Julian calendar, we assume a consistent 4-year leap
  201. * rule, even though the historical pattern of leap years is irregular,
  202. * being every 3 years from 45 BC through 9 BC, then every 4 years from 8 AD
  203. * onwards, with no leap years in-between. Thus date computations and
  204. * functions such as isLeapYear() are not intended to be historically
  205. * accurate.
  206. *
  207. * Given that milliseconds are a long, day numbers such as Julian day
  208. * numbers, Gregorian or Julian calendar days, or epoch days, are also
  209. * longs. Years can fit into an int.
  210. */
  211. //////////////////
  212. // Class Variables
  213. //////////////////
  214. /**
  215. * Value of the <code>ERA</code> field indicating
  216. * the period before the common era (before Christ), also known as BCE.
  217. * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is
  218. * ..., 2 BC, 1 BC, 1 AD, 2 AD,...
  219. * @see Calendar#ERA
  220. */
  221. public static final int BC = 0;
  222. /**
  223. * Value of the <code>ERA</code> field indicating
  224. * the common era (Anno Domini), also known as CE.
  225. * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is
  226. * ..., 2 BC, 1 BC, 1 AD, 2 AD,...
  227. * @see Calendar#ERA
  228. */
  229. public static final int AD = 1;
  230. private static final int JAN_1_1_JULIAN_DAY = 1721426; // January 1, year 1 (Gregorian)
  231. private static final int EPOCH_JULIAN_DAY = 2440588; // January 1, 1970 (Gregorian)
  232. private static final int EPOCH_YEAR = 1970;
  233. private static final int NUM_DAYS[]
  234. = {0,31,59,90,120,151,181,212,243,273,304,334}; // 0-based, for day-in-year
  235. private static final int LEAP_NUM_DAYS[]
  236. = {0,31,60,91,121,152,182,213,244,274,305,335}; // 0-based, for day-in-year
  237. private static final int MONTH_LENGTH[]
  238. = {31,28,31,30,31,30,31,31,30,31,30,31}; // 0-based
  239. private static final int LEAP_MONTH_LENGTH[]
  240. = {31,29,31,30,31,30,31,31,30,31,30,31}; // 0-based
  241. // Useful millisecond constants. Although ONE_DAY and ONE_WEEK can fit
  242. // into ints, they must be longs in order to prevent arithmetic overflow
  243. // when performing (bug 4173516).
  244. private static final int ONE_SECOND = 1000;
  245. private static final int ONE_MINUTE = 60*ONE_SECOND;
  246. private static final int ONE_HOUR = 60*ONE_MINUTE;
  247. private static final long ONE_DAY = 24*ONE_HOUR;
  248. private static final long ONE_WEEK = 7*ONE_DAY;
  249. /*
  250. * <pre>
  251. * Greatest Least
  252. * Field name Minimum Minimum Maximum Maximum
  253. * ---------- ------- ------- ------- -------
  254. * ERA 0 0 1 1
  255. * YEAR 1 1 292269054 292278994
  256. * MONTH 0 0 11 11
  257. * WEEK_OF_YEAR 1 1 52 53
  258. * WEEK_OF_MONTH 0 0 4 6
  259. * DAY_OF_MONTH 1 1 28 31
  260. * DAY_OF_YEAR 1 1 365 366
  261. * DAY_OF_WEEK 1 1 7 7
  262. * DAY_OF_WEEK_IN_MONTH -1 -1 4 6
  263. * AM_PM 0 0 1 1
  264. * HOUR 0 0 11 11
  265. * HOUR_OF_DAY 0 0 23 23
  266. * MINUTE 0 0 59 59
  267. * SECOND 0 0 59 59
  268. * MILLISECOND 0 0 999 999
  269. * ZONE_OFFSET -12* -12* 12* 12*
  270. * DST_OFFSET 0 0 1* 1*
  271. * </pre>
  272. * (*) In units of one-hour
  273. */
  274. private static final int MIN_VALUES[] = {
  275. 0,1,0,1,0,1,1,1,-1,0,0,0,0,0,0,-12*ONE_HOUR,0
  276. };
  277. private static final int LEAST_MAX_VALUES[] = {
  278. 1,292269054,11,52,4,28,365,7,4,1,11,23,59,59,999,12*ONE_HOUR,1*ONE_HOUR
  279. };
  280. private static final int MAX_VALUES[] = {
  281. 1,292278994,11,53,6,31,366,7,6,1,11,23,59,59,999,12*ONE_HOUR,1*ONE_HOUR
  282. };
  283. /////////////////////
  284. // Instance Variables
  285. /////////////////////
  286. /**
  287. * The point at which the Gregorian calendar rules are used, measured in
  288. * milliseconds from the standard epoch. Default is October 15, 1582
  289. * (Gregorian) 00:00:00 UTC or -12219292800000L. For this value, October 4,
  290. * 1582 (Julian) is followed by October 15, 1582 (Gregorian). This
  291. * corresponds to Julian day number 2299161.
  292. * @serial
  293. */
  294. private long gregorianCutover = -12219292800000L;
  295. /**
  296. * Midnight, local time (using this Calendar's TimeZone) at or before the
  297. * gregorianCutover. This is a pure date value with no time of day or
  298. * timezone component.
  299. */
  300. private transient long normalizedGregorianCutover = gregorianCutover;
  301. /**
  302. * The year of the gregorianCutover, with 0 representing
  303. * 1 BC, -1 representing 2 BC, etc.
  304. */
  305. private transient int gregorianCutoverYear = 1582;
  306. // Proclaim serialization compatibility with JDK 1.1
  307. static final long serialVersionUID = -8125100834729963327L;
  308. ///////////////
  309. // Constructors
  310. ///////////////
  311. /**
  312. * Constructs a default GregorianCalendar using the current time
  313. * in the default time zone with the default locale.
  314. */
  315. public GregorianCalendar() {
  316. this(TimeZone.getDefault(), Locale.getDefault());
  317. }
  318. /**
  319. * Constructs a GregorianCalendar based on the current time
  320. * in the given time zone with the default locale.
  321. * @param zone the given time zone.
  322. */
  323. public GregorianCalendar(TimeZone zone) {
  324. this(zone, Locale.getDefault());
  325. }
  326. /**
  327. * Constructs a GregorianCalendar based on the current time
  328. * in the default time zone with the given locale.
  329. * @param aLocale the given locale.
  330. */
  331. public GregorianCalendar(Locale aLocale) {
  332. this(TimeZone.getDefault(), aLocale);
  333. }
  334. /**
  335. * Constructs a GregorianCalendar based on the current time
  336. * in the given time zone with the given locale.
  337. * @param zone the given time zone.
  338. * @param aLocale the given locale.
  339. */
  340. public GregorianCalendar(TimeZone zone, Locale aLocale) {
  341. super(zone, aLocale);
  342. setTimeInMillis(System.currentTimeMillis());
  343. }
  344. /**
  345. * Constructs a GregorianCalendar with the given date set
  346. * in the default time zone with the default locale.
  347. * @param year the value used to set the YEAR time field in the calendar.
  348. * @param month the value used to set the MONTH time field in the calendar.
  349. * Month value is 0-based. e.g., 0 for January.
  350. * @param date the value used to set the DATE time field in the calendar.
  351. */
  352. public GregorianCalendar(int year, int month, int date) {
  353. super(TimeZone.getDefault(), Locale.getDefault());
  354. this.set(YEAR, year);
  355. this.set(MONTH, month);
  356. this.set(DATE, date);
  357. }
  358. /**
  359. * Constructs a GregorianCalendar with the given date
  360. * and time set for the default time zone with the default locale.
  361. * @param year the value used to set the YEAR time field in the calendar.
  362. * @param month the value used to set the MONTH time field in the calendar.
  363. * Month value is 0-based. e.g., 0 for January.
  364. * @param date the value used to set the DATE time field in the calendar.
  365. * @param hour the value used to set the HOUR_OF_DAY time field
  366. * in the calendar.
  367. * @param minute the value used to set the MINUTE time field
  368. * in the calendar.
  369. */
  370. public GregorianCalendar(int year, int month, int date, int hour,
  371. int minute) {
  372. super(TimeZone.getDefault(), Locale.getDefault());
  373. this.set(YEAR, year);
  374. this.set(MONTH, month);
  375. this.set(DATE, date);
  376. this.set(HOUR_OF_DAY, hour);
  377. this.set(MINUTE, minute);
  378. }
  379. /**
  380. * Constructs a GregorianCalendar with the given date
  381. * and time set for the default time zone with the default locale.
  382. * @param year the value used to set the YEAR time field in the calendar.
  383. * @param month the value used to set the MONTH time field in the calendar.
  384. * Month value is 0-based. e.g., 0 for January.
  385. * @param date the value used to set the DATE time field in the calendar.
  386. * @param hour the value used to set the HOUR_OF_DAY time field
  387. * in the calendar.
  388. * @param minute the value used to set the MINUTE time field
  389. * in the calendar.
  390. * @param second the value used to set the SECOND time field
  391. * in the calendar.
  392. */
  393. public GregorianCalendar(int year, int month, int date, int hour,
  394. int minute, int second) {
  395. super(TimeZone.getDefault(), Locale.getDefault());
  396. this.set(YEAR, year);
  397. this.set(MONTH, month);
  398. this.set(DATE, date);
  399. this.set(HOUR_OF_DAY, hour);
  400. this.set(MINUTE, minute);
  401. this.set(SECOND, second);
  402. }
  403. /////////////////
  404. // Public methods
  405. /////////////////
  406. /**
  407. * Sets the GregorianCalendar change date. This is the point when the switch
  408. * from Julian dates to Gregorian dates occurred. Default is October 15,
  409. * 1582. Previous to this, dates will be in the Julian calendar.
  410. * <p>
  411. * To obtain a pure Julian calendar, set the change date to
  412. * <code>Date(Long.MAX_VALUE)</code>. To obtain a pure Gregorian calendar,
  413. * set the change date to <code>Date(Long.MIN_VALUE)</code>.
  414. *
  415. * @param date the given Gregorian cutover date.
  416. */
  417. public void setGregorianChange(Date date) {
  418. gregorianCutover = date.getTime();
  419. // Precompute two internal variables which we use to do the actual
  420. // cutover computations. These are the normalized cutover, which is the
  421. // midnight at or before the cutover, and the cutover year. The
  422. // normalized cutover is in pure date milliseconds; it contains no time
  423. // of day or timezone component, and it used to compare against other
  424. // pure date values.
  425. long cutoverDay = floorDivide(gregorianCutover, ONE_DAY);
  426. normalizedGregorianCutover = cutoverDay * ONE_DAY;
  427. // Handle the rare case of numeric overflow. If the user specifies a
  428. // change of Date(Long.MIN_VALUE), in order to get a pure Gregorian
  429. // calendar, then the epoch day is -106751991168, which when multiplied
  430. // by ONE_DAY gives 9223372036794351616 -- the negative value is too
  431. // large for 64 bits, and overflows into a positive value. We correct
  432. // this by using the next day, which for all intents is semantically
  433. // equivalent.
  434. if (cutoverDay < 0 && normalizedGregorianCutover > 0) {
  435. normalizedGregorianCutover = (cutoverDay + 1) * ONE_DAY;
  436. }
  437. // Normalize the year so BC values are represented as 0 and negative
  438. // values.
  439. GregorianCalendar cal = new GregorianCalendar(getTimeZone());
  440. cal.setTime(date);
  441. gregorianCutoverYear = cal.get(YEAR);
  442. if (cal.get(ERA) == BC) {
  443. gregorianCutoverYear = 1 - gregorianCutoverYear;
  444. }
  445. }
  446. /**
  447. * Gets the Gregorian Calendar change date. This is the point when the
  448. * switch from Julian dates to Gregorian dates occurred. Default is
  449. * October 15, 1582. Previous to this, dates will be in the Julian
  450. * calendar.
  451. * @return the Gregorian cutover date for this calendar.
  452. */
  453. public final Date getGregorianChange() {
  454. return new Date(gregorianCutover);
  455. }
  456. /**
  457. * Determines if the given year is a leap year. Returns true if the
  458. * given year is a leap year.
  459. * @param year the given year.
  460. * @return true if the given year is a leap year; false otherwise.
  461. */
  462. public boolean isLeapYear(int year) {
  463. return year >= gregorianCutoverYear ?
  464. ((year%4 == 0) && ((year%100 != 0) || (year%400 == 0))) : // Gregorian
  465. (year%4 == 0); // Julian
  466. }
  467. /**
  468. * Compares this GregorianCalendar to an object reference.
  469. * @param obj the object reference with which to compare
  470. * @return true if this object is equal to <code>obj</code> false otherwise
  471. */
  472. public boolean equals(Object obj) {
  473. return super.equals(obj) &&
  474. obj instanceof GregorianCalendar &&
  475. gregorianCutover == ((GregorianCalendar)obj).gregorianCutover;
  476. }
  477. /**
  478. * Override hashCode.
  479. * Generates the hash code for the GregorianCalendar object
  480. */
  481. public int hashCode() {
  482. return super.hashCode() ^ (int)gregorianCutover;
  483. }
  484. /**
  485. * Adds the specified (signed) amount of time to the given time field,
  486. * based on the calendar's rules.
  487. * <p><em>Add rule 1</em>. The value of <code>field</code>
  488. * after the call minus the value of <code>field</code> before the
  489. * call is <code>amount</code>, modulo any overflow that has occurred in
  490. * <code>field</code>. Overflow occurs when a field value exceeds its
  491. * range and, as a result, the next larger field is incremented or
  492. * decremented and the field value is adjusted back into its range.</p>
  493. *
  494. * <p><em>Add rule 2</em>. If a smaller field is expected to be
  495. * invariant, but it is impossible for it to be equal to its
  496. * prior value because of changes in its minimum or maximum after
  497. * <code>field</code> is changed, then its value is adjusted to be as close
  498. * as possible to its expected value. A smaller field represents a
  499. * smaller unit of time. <code>HOUR</code> is a smaller field than
  500. * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
  501. * that are not expected to be invariant. The calendar system
  502. * determines what fields are expected to be invariant.</p>
  503. * @param field the time field.
  504. * @param amount the amount of date or time to be added to the field.
  505. * @exception IllegalArgumentException if an unknown field is given.
  506. */
  507. public void add(int field, int amount) {
  508. if (amount == 0) {
  509. return; // Do nothing!
  510. }
  511. complete();
  512. if (field == YEAR) {
  513. int year = this.internalGet(YEAR);
  514. if (this.internalGetEra() == AD) {
  515. year += amount;
  516. if (year > 0) {
  517. this.set(YEAR, year);
  518. } else { // year <= 0
  519. this.set(YEAR, 1 - year);
  520. // if year == 0, you get 1 BC
  521. this.set(ERA, BC);
  522. }
  523. }
  524. else { // era == BC
  525. year -= amount;
  526. if (year > 0) {
  527. this.set(YEAR, year);
  528. } else { // year <= 0
  529. this.set(YEAR, 1 - year);
  530. // if year == 0, you get 1 AD
  531. this.set(ERA, AD);
  532. }
  533. }
  534. pinDayOfMonth();
  535. } else if (field == MONTH) {
  536. int month = this.internalGet(MONTH) + amount;
  537. int year = this.internalGet(YEAR);
  538. int y_amount;
  539. if (month >= 0) {
  540. y_amount = month12;
  541. } else {
  542. y_amount = (month+1)/12 - 1;
  543. }
  544. if (y_amount != 0) {
  545. if (this.internalGetEra() == AD) {
  546. year += y_amount;
  547. if (year > 0) {
  548. this.set(YEAR, year);
  549. } else { // year <= 0
  550. this.set(YEAR, 1 - year);
  551. // if year == 0, you get 1 BC
  552. this.set(ERA, BC);
  553. }
  554. }
  555. else { // era == BC
  556. year -= y_amount;
  557. if (year > 0) {
  558. this.set(YEAR, year);
  559. } else { // year <= 0
  560. this.set(YEAR, 1 - year);
  561. // if year == 0, you get 1 AD
  562. this.set(ERA, AD);
  563. }
  564. }
  565. }
  566. if (month >= 0) {
  567. set(MONTH, (int) (month % 12));
  568. } else {
  569. // month < 0
  570. month %= 12;
  571. if (month < 0) {
  572. month += 12;
  573. }
  574. set(MONTH, JANUARY + month);
  575. }
  576. pinDayOfMonth();
  577. } else if (field == ERA) {
  578. int era = internalGet(ERA) + amount;
  579. if (era < 0) {
  580. era = 0;
  581. }
  582. if (era > 1) {
  583. era = 1;
  584. }
  585. set(ERA, era);
  586. } else {
  587. // We handle most fields here. The algorithm is to add a computed amount
  588. // of millis to the current millis. The only wrinkle is with DST -- if
  589. // the result of the add operation is to move from DST to Standard, or vice
  590. // versa, we need to adjust by an hour forward or back, respectively.
  591. // Otherwise you get weird effects in which the hour seems to shift when
  592. // you add to the DAY_OF_MONTH field, for instance.
  593. // We only adjust the DST for fields larger than an hour. For fields
  594. // smaller than an hour, we cannot adjust for DST without causing problems.
  595. // for instance, if you add one hour to April 5, 1998, 1:00 AM, in PST,
  596. // the time becomes "2:00 AM PDT" (an illegal value), but then the adjustment
  597. // sees the change and compensates by subtracting an hour. As a result the
  598. // time doesn't advance at all.
  599. long delta = amount;
  600. boolean adjustDST = true;
  601. switch (field) {
  602. case WEEK_OF_YEAR:
  603. case WEEK_OF_MONTH:
  604. case DAY_OF_WEEK_IN_MONTH:
  605. delta *= 7 * 24 * 60 * 60 * 1000; // 7 days
  606. break;
  607. case AM_PM:
  608. delta *= 12 * 60 * 60 * 1000; // 12 hrs
  609. break;
  610. case DATE: // synonym of DAY_OF_MONTH
  611. case DAY_OF_YEAR:
  612. case DAY_OF_WEEK:
  613. delta *= 24 * 60 * 60 * 1000; // 1 day
  614. break;
  615. case HOUR_OF_DAY:
  616. case HOUR:
  617. delta *= 60 * 60 * 1000; // 1 hour
  618. adjustDST = false;
  619. break;
  620. case MINUTE:
  621. delta *= 60 * 1000; // 1 minute
  622. adjustDST = false;
  623. break;
  624. case SECOND:
  625. delta *= 1000; // 1 second
  626. adjustDST = false;
  627. break;
  628. case MILLISECOND:
  629. adjustDST = false;
  630. break;
  631. case ZONE_OFFSET:
  632. case DST_OFFSET:
  633. default:
  634. throw new IllegalArgumentException();
  635. }
  636. // Save the current DST state.
  637. long dst = 0;
  638. if (adjustDST) {
  639. dst = internalGet(DST_OFFSET);
  640. }
  641. setTimeInMillis(time + delta); // Automatically computes fields if necessary
  642. if (adjustDST) {
  643. // Now do the DST adjustment alluded to above.
  644. // Only call setTimeInMillis if necessary, because it's an expensive call.
  645. dst -= internalGet(DST_OFFSET);
  646. if (dst != 0) {
  647. setTimeInMillis(time + dst);
  648. }
  649. }
  650. }
  651. }
  652. /**
  653. * Adds or subtracts (up/down) a single unit of time on the given time
  654. * field without changing larger fields.
  655. * <p>
  656. * <em>Example</em>: Consider a <code>GregorianCalendar</code>
  657. * originally set to December 31, 1999. Calling <code>roll(Calendar.MONTH, true)</code>
  658. * sets the calendar to January 31, 1999. The <code>Year</code> field is unchanged
  659. * because it is a larger field than <code>MONTH</code>.</p>
  660. * @param up indicates if the value of the specified time field is to be
  661. * rolled up or rolled down. Use true if rolling up, false otherwise.
  662. * @exception IllegalArgumentException if an unknown field value is given.
  663. * @see GregorianCalendar#add
  664. * @see GregorianCalendar#set
  665. */
  666. public void roll(int field, boolean up) {
  667. roll(field, up ? +1 : -1);
  668. }
  669. /**
  670. * Add to field a signed amount without changing larger fields.
  671. * A negative roll amount means to subtract from field without changing
  672. * larger fields.
  673. * <p>
  674. * <em>Example</em>: Consider a <code>GregorianCalendar</code>
  675. * originally set to August 31, 1999. Calling <code>roll(Calendar.MONTH,
  676. * 8)</code> sets the calendar to April 30, <strong>1999</strong>. Using a
  677. * <code>GregorianCalendar</code>, the <code>DAY_OF_MONTH</code> field cannot
  678. * be 31 in the month April. <code>DAY_OF_MONTH</code> is set to the closest possible
  679. * value, 30. The <code>YEAR</code> field maintains the value of 1999 because it
  680. * is a larger field than <code>MONTH</code>.
  681. * <p>
  682. * <em>Example</em>: Consider a <code>GregorianCalendar</code>
  683. * originally set to Sunday June 6, 1999. Calling
  684. * <code>roll(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to
  685. * Tuesday June 1, 1999, whereas calling
  686. * <code>add(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to
  687. * Sunday May 30, 1999. This is because the roll rule imposes an
  688. * additional constraint: The <code>MONTH</code> must not change when the
  689. * <code>WEEK_OF_MONTH</code> is rolled. Taken together with add rule 1,
  690. * the resultant date must be between Tuesday June 1 and Saturday June
  691. * 5. According to add rule 2, the <code>DAY_OF_WEEK</code>, an invariant
  692. * when changing the <code>WEEK_OF_MONTH</code>, is set to Tuesday, the
  693. * closest possible value to Sunday (where Sunday is the first day of the
  694. * week).</p>
  695. * @param field the time field.
  696. * @param amount the signed amount to add to <code>field</code>.
  697. * @since 1.2
  698. * @see GregorianCalendar#add
  699. * @see GregorianCalendar#set
  700. */
  701. public void roll(int field, int amount) {
  702. if (amount == 0) {
  703. return; // Nothing to do
  704. }
  705. int min = 0, max = 0, gap;
  706. if (field >= 0 && field < FIELD_COUNT) {
  707. complete();
  708. min = getMinimum(field);
  709. max = getMaximum(field);
  710. }
  711. switch (field) {
  712. case ERA:
  713. case YEAR:
  714. case AM_PM:
  715. case MINUTE:
  716. case SECOND:
  717. case MILLISECOND:
  718. // These fields are handled simply, since they have fixed minima
  719. // and maxima. The field DAY_OF_MONTH is almost as simple. Other
  720. // fields are complicated, since the range within they must roll
  721. // varies depending on the date.
  722. break;
  723. case HOUR:
  724. case HOUR_OF_DAY:
  725. // Rolling the hour is difficult on the ONSET and CEASE days of
  726. // daylight savings. For example, if the change occurs at
  727. // 2 AM, we have the following progression:
  728. // ONSET: 12 Std -> 1 Std -> 3 Dst -> 4 Dst
  729. // CEASE: 12 Dst -> 1 Dst -> 1 Std -> 2 Std
  730. // To get around this problem we don't use fields; we manipulate
  731. // the time in millis directly.
  732. {
  733. // Assume min == 0 in calculations below
  734. Date start = getTime();
  735. int oldHour = internalGet(field);
  736. int newHour = (oldHour + amount) % (max + 1);
  737. if (newHour < 0) {
  738. newHour += max + 1;
  739. }
  740. setTime(new Date(start.getTime() + ONE_HOUR * (newHour - oldHour)));
  741. return;
  742. }
  743. case MONTH:
  744. // Rolling the month involves both pinning the final value to [0, 11]
  745. // and adjusting the DAY_OF_MONTH if necessary. We only adjust the
  746. // DAY_OF_MONTH if, after updating the MONTH field, it is illegal.
  747. // E.g., <jan31>.roll(MONTH, 1) -> <feb28> or <feb29>.
  748. {
  749. int mon = (internalGet(MONTH) + amount) % 12;
  750. if (mon < 0) {
  751. mon += 12;
  752. }
  753. set(MONTH, mon);
  754. // Keep the day of month in range. We don't want to spill over
  755. // into the next month; e.g., we don't want jan31 + 1 mo -> feb31 ->
  756. // mar3.
  757. // NOTE: We could optimize this later by checking for dom <= 28
  758. // first. Do this if there appears to be a need. [LIU]
  759. int monthLen = monthLength(mon);
  760. int dom = internalGet(DAY_OF_MONTH);
  761. if (dom > monthLen) {
  762. set(DAY_OF_MONTH, monthLen);
  763. }
  764. return;
  765. }
  766. case WEEK_OF_YEAR:
  767. {
  768. // Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the
  769. // week. Also, rolling the week of the year can have seemingly
  770. // strange effects simply because the year of the week of year
  771. // may be different from the calendar year. For example, the
  772. // date Dec 28, 1997 is the first day of week 1 of 1998 (if
  773. // weeks start on Sunday and the minimal days in first week is
  774. // <= 3).
  775. int woy = internalGet(WEEK_OF_YEAR);
  776. // Get the ISO year, which matches the week of year. This
  777. // may be one year before or after the calendar year.
  778. int isoYear = internalGet(YEAR);
  779. int isoDoy = internalGet(DAY_OF_YEAR);
  780. if (internalGet(MONTH) == Calendar.JANUARY) {
  781. if (woy >= 52) {
  782. --isoYear;
  783. isoDoy += yearLength(isoYear);
  784. }
  785. } else {
  786. if (woy == 1) {
  787. isoDoy -= yearLength(isoYear);
  788. ++isoYear;
  789. }
  790. }
  791. woy += amount;
  792. // Do fast checks to avoid unnecessary computation:
  793. if (woy < 1 || woy > 52) {
  794. // Determine the last week of the ISO year.
  795. // First, we calculate the relative fractional days of the
  796. // last week of the year. (This doesn't include days in
  797. // the year before or after the calendar year.)
  798. int lastDoy = yearLength(isoYear);
  799. int normalizedDayOfWeek = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
  800. if (normalizedDayOfWeek < 0) {
  801. normalizedDayOfWeek += 7;
  802. }
  803. int lastRelDow = (lastDoy - isoDoy + normalizedDayOfWeek) % 7;
  804. if (lastRelDow < 0) {
  805. lastRelDow += 7;
  806. }
  807. // Next, calculate the minimal last week of year.
  808. // Now this value is just the total number of weeks in the
  809. // year all of which have 7 days a week. Need to check the
  810. // first and the last week of the year, which would have
  811. // days fewer than 7.
  812. int lastWoy;
  813. lastDoy -= (lastRelDow+1);
  814. lastWoy = lastDoy / 7;
  815. // If the relative fraction of the first week of the year
  816. // is more than MinimalDaysInFirstWeek, add 1 to the last
  817. // week // of the year.
  818. if ((lastDoy - (lastWoy*7)) >= getMinimalDaysInFirstWeek()) {
  819. lastWoy++;
  820. }
  821. // If the relative fraction of the last week of the year
  822. // is more than MinimalDaysInFirstWeek, add 1 to the last
  823. // week of the year.
  824. if ((6 - lastRelDow) < getMinimalDaysInFirstWeek()) {
  825. lastWoy++;
  826. }
  827. woy = ((woy + lastWoy - 1) % lastWoy) + 1;
  828. }
  829. set(WEEK_OF_YEAR, woy);
  830. set(YEAR, isoYear);
  831. return;
  832. }
  833. case WEEK_OF_MONTH:
  834. {
  835. // This is tricky, because during the roll we may have to shift
  836. // to a different day of the week. For example:
  837. // s m t w r f s
  838. // 1 2 3 4 5
  839. // 6 7 8 9 10 11 12
  840. // When rolling from the 6th or 7th back one week, we go to the
  841. // 1st (assuming that the first partial week counts). The same
  842. // thing happens at the end of the month.
  843. // The other tricky thing is that we have to figure out whether
  844. // the first partial week actually counts or not, based on the
  845. // minimal first days in the week. And we have to use the
  846. // correct first day of the week to delineate the week
  847. // boundaries.
  848. // Here's our algorithm. First, we find the real boundaries of
  849. // the month. Then we discard the first partial week if it
  850. // doesn't count in this locale. Then we fill in the ends with
  851. // phantom days, so that the first partial week and the last
  852. // partial week are full weeks. We then have a nice square
  853. // block of weeks. We do the usual rolling within this block,
  854. // as is done elsewhere in this method. If we wind up on one of
  855. // the phantom days that we added, we recognize this and pin to
  856. // the first or the last day of the month. Easy, eh?
  857. // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
  858. // in this locale. We have dow in 0..6.
  859. int dow = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
  860. if (dow < 0) {
  861. dow += 7;
  862. }
  863. // Find the day of the week (normalized for locale) for the first
  864. // of the month.
  865. int fdm = (dow - internalGet(DAY_OF_MONTH) + 1) % 7;
  866. if (fdm < 0) {
  867. fdm += 7;
  868. }
  869. // Get the first day of the first full week of the month,
  870. // including phantom days, if any. Figure out if the first week
  871. // counts or not; if it counts, then fill in phantom days. If
  872. // not, advance to the first real full week (skip the partial week).
  873. int start;
  874. if ((7 - fdm) < getMinimalDaysInFirstWeek()) {
  875. start = 8 - fdm; // Skip the first partial week
  876. } else {
  877. start = 1 - fdm; // This may be zero or negative
  878. }
  879. // Get the day of the week (normalized for locale) for the last
  880. // day of the month.
  881. int monthLen = monthLength(internalGet(MONTH));
  882. int ldm = (monthLen - internalGet(DAY_OF_MONTH) + dow) % 7;
  883. // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here.
  884. // Get the limit day for the blocked-off rectangular month; that
  885. // is, the day which is one past the last day of the month,
  886. // after the month has already been filled in with phantom days
  887. // to fill out the last week. This day has a normalized DOW of 0.
  888. int limit = monthLen + 7 - ldm;
  889. // Now roll between start and (limit - 1).
  890. gap = limit - start;
  891. int day_of_month = (internalGet(DAY_OF_MONTH) + amount*7 -
  892. start) % gap;
  893. if (day_of_month < 0) {
  894. day_of_month += gap;
  895. }
  896. day_of_month += start;
  897. // Finally, pin to the real start and end of the month.
  898. if (day_of_month < 1) {
  899. day_of_month = 1;
  900. }
  901. if (day_of_month > monthLen) {
  902. day_of_month = monthLen;
  903. }
  904. // Set the DAY_OF_MONTH. We rely on the fact that this field
  905. // takes precedence over everything else (since all other fields
  906. // are also set at this point). If this fact changes (if the
  907. // disambiguation algorithm changes) then we will have to unset
  908. // the appropriate fields here so that DAY_OF_MONTH is attended
  909. // to.
  910. set(DAY_OF_MONTH, day_of_month);
  911. return;
  912. }
  913. case DAY_OF_MONTH:
  914. max = monthLength(internalGet(MONTH));
  915. break;
  916. case DAY_OF_YEAR:
  917. {
  918. // Roll the day of year using millis. Compute the millis for
  919. // the start of the year, and get the length of the year.
  920. long delta = amount * ONE_DAY; // Scale up from days to millis
  921. long min2 = time - (internalGet(DAY_OF_YEAR) - 1) * ONE_DAY;
  922. int yearLength = yearLength();
  923. time = (time + delta - min2) % (yearLength*ONE_DAY);
  924. if (time < 0) {
  925. time += yearLength*ONE_DAY;
  926. }
  927. long dst = internalGet(DST_OFFSET);
  928. setTimeInMillis(time + min2);
  929. dst -= internalGet(DST_OFFSET);
  930. if (dst != 0) {
  931. setTimeInMillis(time + dst);
  932. }
  933. return;
  934. }
  935. case DAY_OF_WEEK:
  936. {
  937. // Roll the day of week using millis. Compute the millis for
  938. // the start of the week, using the first day of week setting.
  939. // Restrict the millis to [start, start+7days).
  940. long delta = amount * ONE_DAY; // Scale up from days to millis
  941. // Compute the number of days before the current day in this
  942. // week. This will be a value 0..6.
  943. int leadDays = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
  944. if (leadDays < 0) {
  945. leadDays += 7;
  946. }
  947. long min2 = time - leadDays * ONE_DAY;
  948. time = (time + delta - min2) % ONE_WEEK;
  949. if (time < 0) {
  950. time += ONE_WEEK;
  951. }
  952. long dst = internalGet(DST_OFFSET);
  953. setTimeInMillis(time + min2);
  954. dst -= internalGet(DST_OFFSET);
  955. if (dst != 0) {
  956. setTimeInMillis(time + dst);
  957. }
  958. return;
  959. }
  960. case DAY_OF_WEEK_IN_MONTH:
  961. {
  962. // Roll the day of week in the month using millis. Determine
  963. // the first day of the week in the month, and then the last,
  964. // and then roll within that range.
  965. long delta = amount * ONE_WEEK; // Scale up from weeks to millis
  966. // Find the number of same days of the week before this one
  967. // in this month.
  968. int preWeeks = (internalGet(DAY_OF_MONTH) - 1) / 7;
  969. // Find the number of same days of the week after this one
  970. // in this month.
  971. int postWeeks = (monthLength(internalGet(MONTH)) -
  972. internalGet(DAY_OF_MONTH)) / 7;
  973. // From these compute the min and gap millis for rolling.
  974. long min2 = time - preWeeks * ONE_WEEK;
  975. long gap2 = ONE_WEEK * (preWeeks + postWeeks + 1); // Must add 1!
  976. // Roll within this range
  977. time = (time + delta - min2) % gap2;
  978. if (time < 0) {
  979. time += gap2;
  980. }
  981. long dst = internalGet(DST_OFFSET);
  982. setTimeInMillis(time + min2);
  983. dst -= internalGet(DST_OFFSET);
  984. if (dst != 0) {
  985. setTimeInMillis(time + dst);
  986. }
  987. return;
  988. }
  989. case ZONE_OFFSET:
  990. case DST_OFFSET:
  991. default:
  992. // These fields cannot be rolled
  993. throw new IllegalArgumentException();
  994. }
  995. // These are the standard roll instructions. These work for all
  996. // simple cases, that is, cases in which the limits are fixed, such
  997. // as the hour, the month, and the era.
  998. gap = max - min + 1;
  999. int value = internalGet(field) + amount;
  1000. value = (value - min) % gap;
  1001. if (value < 0) {
  1002. value += gap;
  1003. }
  1004. value += min;
  1005. set(field, value);
  1006. }
  1007. /**
  1008. * Returns minimum value for the given field.
  1009. * e.g. for Gregorian DAY_OF_MONTH, 1
  1010. * Please see Calendar.getMinimum for descriptions on parameters and
  1011. * the return value.
  1012. */
  1013. public int getMinimum(int field) {
  1014. return MIN_VALUES[field];
  1015. }
  1016. /**
  1017. * Returns maximum value for the given field.
  1018. * e.g. for Gregorian DAY_OF_MONTH, 31
  1019. * Please see Calendar.getMaximum for descriptions on parameters and
  1020. * the return value.
  1021. */
  1022. public int getMaximum(int field) {
  1023. return MAX_VALUES[field];
  1024. }
  1025. /**
  1026. * Returns highest minimum value for the given field if varies.
  1027. * Otherwise same as getMinimum(). For Gregorian, no difference.
  1028. * Please see Calendar.getGreatestMinimum for descriptions on parameters
  1029. * and the return value.
  1030. */
  1031. public int getGreatestMinimum(int field) {
  1032. return MIN_VALUES[field];
  1033. }
  1034. /**
  1035. * Returns lowest maximum value for the given field if varies.
  1036. * Otherwise same as getMaximum(). For Gregorian DAY_OF_MONTH, 28
  1037. * Please see Calendar.getLeastMaximum for descriptions on parameters and
  1038. * the return value.
  1039. */
  1040. public int getLeastMaximum(int field) {
  1041. return LEAST_MAX_VALUES[field];
  1042. }
  1043. /**
  1044. * Return the minimum value that this field could have, given the current date.
  1045. * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
  1046. * @since 1.2
  1047. */
  1048. public int getActualMinimum(int field) {
  1049. return getMinimum(field);
  1050. }
  1051. /**
  1052. * Return the maximum value that this field could have, given the current date.
  1053. * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
  1054. * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar,
  1055. * for some years the actual maximum for MONTH is 12, and for others 13.
  1056. * @since 1.2
  1057. */
  1058. public int getActualMaximum(int field) {
  1059. /* It is a known limitation that the code here (and in getActualMinimum)
  1060. * won't behave properly at the extreme limits of GregorianCalendar's
  1061. * representable range (except for the code that handles the YEAR
  1062. * field). That's because the ends of the representable range are at
  1063. * odd spots in the year. For calendars with the default Gregorian
  1064. * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun
  1065. * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT
  1066. * zones. As a result, if the calendar is set to Aug 1 292278994 AD,
  1067. * the actual maximum of DAY_OF_MONTH is 17, not 30. If the date is Mar
  1068. * 31 in that year, the actual maximum month might be Jul, whereas is
  1069. * the date is Mar 15, the actual maximum might be Aug -- depending on
  1070. * the precise semantics that are desired. Similar considerations
  1071. * affect all fields. Nonetheless, this effect is sufficiently arcane
  1072. * that we permit it, rather than complicating the code to handle such
  1073. * intricacies. - liu 8/20/98 */
  1074. switch (field) {
  1075. // we have functions that enable us to fast-path number of days in month
  1076. // of year
  1077. case DAY_OF_MONTH:
  1078. return monthLength(get(MONTH));
  1079. case DAY_OF_YEAR:
  1080. return yearLength();
  1081. // for week of year, week of month, or day of week in month, we
  1082. // just fall back on the default implementation in Calendar (I'm not sure
  1083. // we could do better by having special calculations here)
  1084. case WEEK_OF_YEAR:
  1085. case WEEK_OF_MONTH:
  1086. case DAY_OF_WEEK_IN_MONTH:
  1087. return super.getActualMaximum(field);
  1088. case YEAR:
  1089. /* The year computation is no different, in principle, from the
  1090. * others, however, the range of possible maxima is large. In
  1091. * addition, the way we know we've exceeded the range is different.
  1092. * For these reasons, we use the special case code below to handle
  1093. * this field.
  1094. *
  1095. * The actual maxima for YEAR depend on the type of calendar:
  1096. *
  1097. * Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD
  1098. * Julian = Dec 2, 292269055 BC - Jan 3, 292272993 AD
  1099. * Hybrid = Dec 2, 292269055 BC - Aug 17, 292278994 AD
  1100. *
  1101. * We know we've exceeded the maximum when either the month, date,
  1102. * time, or era changes in response to setting the year. We don't
  1103. * check for month, date, and time here because the year and era are
  1104. * sufficient to detect an invalid year setting. NOTE: If code is
  1105. * added to check the month and date in the future for some reason,
  1106. * Feb 29 must be allowed to shift to Mar 1 when setting the year.
  1107. */
  1108. {
  1109. Calendar cal = (Calendar)this.clone();
  1110. cal.setLenient(true);
  1111. int era = cal.get(ERA);
  1112. Date d = cal.getTime();
  1113. /* Perform a binary search, with the invariant that lowGood is a
  1114. * valid year, and highBad is an out of range year.
  1115. */
  1116. int lowGood = LEAST_MAX_VALUES[YEAR];
  1117. int highBad = MAX_VALUES[YEAR] + 1;
  1118. while ((lowGood + 1) < highBad) {
  1119. int y = (lowGood + highBad) / 2;
  1120. cal.set(YEAR, y);
  1121. if (cal.get(YEAR) == y && cal.get(ERA) == era) {
  1122. lowGood = y;
  1123. } else {
  1124. highBad = y;
  1125. cal.setTime(d); // Restore original fields
  1126. }
  1127. }
  1128. return lowGood;
  1129. }
  1130. // and we know none of the other fields have variable maxima in
  1131. // GregorianCalendar, so we can just return the fixed maximum
  1132. default:
  1133. return getMaximum(field);
  1134. }
  1135. }
  1136. //////////////////////
  1137. // Proposed public API
  1138. //////////////////////
  1139. /**
  1140. * Return true if the current time for this Calendar is in Daylignt
  1141. * Savings Time.
  1142. *
  1143. * Note -- MAKE THIS PUBLIC AT THE NEXT API CHANGE. POSSIBLY DEPRECATE
  1144. * AND REMOVE TimeZone.inDaylightTime().
  1145. */
  1146. boolean inDaylightTime() {
  1147. if (!getTimeZone().useDaylightTime()) {
  1148. return false;
  1149. }
  1150. complete(); // Force update of DST_OFFSET field
  1151. return internalGet(DST_OFFSET) != 0;
  1152. }
  1153. /**
  1154. * Return the year that corresponds to the <code>WEEK_OF_YEAR</code> field.
  1155. * This may be one year before or after the calendar year stored
  1156. * in the <code>YEAR</code> field. For example, January 1, 1999 is considered
  1157. * Friday of week 53 of 1998 (if minimal days in first week is
  1158. * 2 or less, and the first day of the week is Sunday). Given
  1159. * these same settings, the ISO year of January 1, 1999 is
  1160. * 1998.
  1161. * <p>
  1162. * Warning: This method will complete all fields.
  1163. * @return the year corresponding to the <code>WEEK_OF_YEAR</code> field, which
  1164. * may be one year before or after the <code>YEAR</code> field.
  1165. * @see #WEEK_OF_YEAR
  1166. */
  1167. int getISOYear() {
  1168. complete();
  1169. int woy = internalGet(WEEK_OF_YEAR);
  1170. // Get the ISO year, which matches the week of year. This
  1171. // may be one year before or after the calendar year.
  1172. int isoYear = internalGet(YEAR);
  1173. if (internalGet(MONTH) == Calendar.JANUARY) {
  1174. if (woy >= 52) {
  1175. --isoYear;
  1176. }
  1177. } else {
  1178. if (woy == 1) {
  1179. ++isoYear;
  1180. }
  1181. }
  1182. return isoYear;
  1183. }
  1184. /////////////////////////////
  1185. // Time => Fields computation
  1186. /////////////////////////////
  1187. /**
  1188. * Converts UTC as milliseconds to time field values.
  1189. * The time is <em>not</em>
  1190. * recomputed first; to recompute the time, then the fields, call the
  1191. * <code>complete</code> method.
  1192. * @see Calendar#complete
  1193. */
  1194. protected void computeFields() {
  1195. computeFieldsImpl();
  1196. // Careful here: We are manually setting the time stamps[]
  1197. // flags to INTERNALLY_SET, so we must be sure that the
  1198. // computeFieldsImpl method actually does set all the fields.
  1199. for (int i = 0; i < FIELD_COUNT; ++i) {
  1200. stamp[i] = INTERNALLY_SET;
  1201. isSet[i] = true;
  1202. }
  1203. }
  1204. /**
  1205. * This computeFieldsImpl implements the conversion from UTC (a
  1206. * millisecond offset from 1970-01-01T00:00:00.000Z) to calendar
  1207. * field values.
  1208. */
  1209. private void computeFieldsImpl() {
  1210. TimeZone tz = getTimeZone();
  1211. int[] offsets = new int[2];
  1212. int offset;
  1213. if (tz instanceof ZoneInfo) {
  1214. offset = ((ZoneInfo)tz).getOffsets(time, offsets);
  1215. } else {
  1216. offset = tz.getOffsets(time, offsets);
  1217. }
  1218. long localMillis = time + offset; // here localMillis is wall
  1219. /* Check for very extreme values -- millis near Long.MIN_VALUE or
  1220. * Long.MAX_VALUE. For these values, adding the zone offset can push
  1221. * the millis past MAX_VALUE to MIN_VALUE, or vice versa. This produces
  1222. * the undesirable effect that the time can wrap around at the ends,
  1223. * yielding, for example, a Date(Long.MAX_VALUE) with a big BC year
  1224. * (should be AD). Handle this by pinning such values to Long.MIN_VALUE
  1225. * or Long.MAX_VALUE. - liu 8/11/98 bug 4149677 */
  1226. if (time > 0 && localMillis < 0 && offset > 0) {
  1227. localMillis = Long.MAX_VALUE;
  1228. } else if (time < 0 && localMillis > 0 && offset < 0) {
  1229. localMillis = Long.MIN_VALUE;
  1230. }
  1231. // Time to fields takes the wall millis (Standard or DST).
  1232. timeToFields(localMillis, false);
  1233. long days = floorDivide(localMillis, ONE_DAY);
  1234. int millisInDay = (int) (localMillis - (days * ONE_DAY));
  1235. if (millisInDay < 0) {
  1236. millisInDay += ONE_DAY;
  1237. }
  1238. // Fill in all time-related fields based on millisInDay. Call internalSet()
  1239. // so as not to perturb flags.
  1240. internalSet(MILLISECOND, millisInDay % 1000);
  1241. millisInDay /= 1000;
  1242. internalSet(SECOND, millisInDay % 60);
  1243. millisInDay /= 60;
  1244. internalSet(MINUTE, millisInDay % 60);
  1245. millisInDay /= 60;
  1246. internalSet(HOUR_OF_DAY, millisInDay);
  1247. internalSet(AM_PM, millisInDay / 12); // Assume AM == 0
  1248. internalSet(HOUR, millisInDay % 12);
  1249. internalSet(ZONE_OFFSET, offsets[0]);
  1250. internalSet(DST_OFFSET, offsets[1]);
  1251. }
  1252. /**
  1253. * Convert the time as milliseconds to the date fields. Millis must be
  1254. * given as local wall millis to get the correct local day. For example,
  1255. * if it is 11:30 pm Standard, and DST is in effect, the correct DST millis
  1256. * must be passed in to get the right date.
  1257. * <p>
  1258. * Fields that are completed by this method: ERA, YEAR, MONTH, DATE,
  1259. * DAY_OF_WEEK, DAY_OF_YEAR, WEEK_OF_YEAR, WEEK_OF_MONTH,
  1260. * DAY_OF_WEEK_IN_MONTH.
  1261. * @param theTime the wall-clock time in milliseconds (either Standard or DST),
  1262. * whichever is in effect
  1263. * @param quick if true, only compute the ERA, YEAR, MONTH, DATE,
  1264. * DAY_OF_WEEK, and DAY_OF_YEAR.
  1265. */
  1266. private final void timeToFields(long theTime, boolean quick) {
  1267. int rawYear, year, month, date, dayOfWeek, dayOfYear, weekCount, era;
  1268. boolean isLeap;
  1269. // Compute the year, month, and day of month from the given millis
  1270. if (theTime >= normalizedGregorianCutover) {
  1271. // The Gregorian epoch day is zero for Monday January 1, year 1.
  1272. long gregorianEpochDay = millisToJulianDay(theTime) - JAN_1_1_JULIAN_DAY;
  1273. // Here we convert from the day number to the multiple radix
  1274. // representation. We use 400-year, 100-year, and 4-year cycles.
  1275. // For example, the 4-year cycle has 4 years + 1 leap day; giving
  1276. // 1461 == 365*4 + 1 days.
  1277. int n400, n100, n4, n1;
  1278. if (gregorianEpochDay > 0) {
  1279. n400 = (int)(gregorianEpochDay / 146097);
  1280. dayOfYear = (int)(gregorianEpochDay % 146097);
  1281. n100 = dayOfYear / 36524;
  1282. dayOfYear %= 36524;
  1283. n4 = dayOfYear / 1461;
  1284. dayOfYear %= 1461;
  1285. n1 = dayOfYear / 365;
  1286. dayOfYear %= 365; // zero-based day of year
  1287. } else {
  1288. int[] rem = new int[1];
  1289. n400 = floorDivide(gregorianEpochDay, 146097, rem); // 400-year cycle length
  1290. n100 = floorDivide(rem[0], 36524, rem); // 100-year cycle length
  1291. n4 = floorDivide(rem[0], 1461, rem); // 4-year cycle length
  1292. n1 = floorDivide(rem[0], 365, rem);
  1293. dayOfYear = rem[0]; // zero-based day of year
  1294. }
  1295. rawYear = 400*n400 + 100*n100 + 4*n4 + n1;
  1296. if (n100 == 4 || n1 == 4) {
  1297. dayOfYear = 365; // Dec 31 at end of 4- or 400-yr cycle
  1298. } else {
  1299. ++rawYear;
  1300. }
  1301. isLeap = ((rawYear&0x3) == 0) && // equiv. to (rawYear%4 == 0)
  1302. (rawYear%100 != 0 || rawYear%400 == 0);
  1303. // Gregorian day zero is a Monday
  1304. dayOfWeek = (int)((gregorianEpochDay+1) % 7);
  1305. } else {
  1306. // The Julian epoch day (not the same as Julian Day)
  1307. // is zero on Saturday December 30, 0 (Gregorian).
  1308. long julianEpochDay = millisToJulianDay(theTime) - (JAN_1_1_JULIAN_DAY - 2);
  1309. rawYear = (int) floorDivide(4*julianEpochDay + 1464, 1461);
  1310. // Compute the Julian calendar day number for January 1, rawYear
  1311. long january1 = 365*(rawYear-1) + floorDivide(rawYear-1, 4);
  1312. dayOfYear = (int)(julianEpochDay - january1); // 0-based
  1313. // Julian leap years occurred historically every 4 years starting
  1314. // with 8 AD. Before 8 AD the spacing is irregular; every 3 years
  1315. // from 45 BC to 9 BC, and then none until 8 AD. However, we don't
  1316. // implement this historical detail; instead, we implement the
  1317. // computationally cleaner proleptic calendar, which assumes
  1318. // consistent 4-year cycles throughout time.
  1319. isLeap = ((rawYear&0x3) == 0); // equiv. to (rawYear%4 == 0)
  1320. // Julian calendar day zero is a Saturday
  1321. dayOfWeek = (int)((julianEpochDay-1) % 7);
  1322. }
  1323. // Common Julian/Gregorian calculation
  1324. int correction = 0;
  1325. int march1 = isLeap ? 60 : 59; // zero-based DOY for March 1
  1326. if (dayOfYear >= march1) {
  1327. correction = isLeap ? 1 : 2;
  1328. }
  1329. month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month
  1330. date = dayOfYear -
  1331. (isLeap ? LEAP_NUM_DAYS[month] : NUM_DAYS[month]) + 1; // one-based DOM
  1332. // Normalize day of week
  1333. dayOfWeek += (dayOfWeek < 0) ? (SUNDAY+7) : SUNDAY;
  1334. era = AD;
  1335. year = rawYear;
  1336. if (year < 1) {
  1337. era = BC;
  1338. year = 1 - year;
  1339. }
  1340. internalSet(ERA, era);
  1341. internalSet(YEAR, year);
  1342. internalSet(MONTH, month + JANUARY); // 0-based
  1343. internalSet(DATE, date);
  1344. internalSet(DAY_OF_WEEK, dayOfWeek);
  1345. internalSet(DAY_OF_YEAR, ++dayOfYear); // Convert from 0-based to 1-based
  1346. if (quick) {
  1347. return;
  1348. }
  1349. // WEEK_OF_YEAR start
  1350. // Compute the week of the year. Valid week numbers run from 1 to 52
  1351. // or 53, depending on the year, the first day of the week, and the
  1352. // minimal days in the first week. Days at the start of the year may
  1353. // fall into the last week of the previous year; days at the end of
  1354. // the year may fall into the first week of the next year.
  1355. int relDow = (dayOfWeek + 7 - getFirstDayOfWeek()) % 7; // 0..6
  1356. int relDowJan1 = (dayOfWeek - dayOfYear + 701 - getFirstDayOfWeek()) % 7; // 0..6
  1357. int woy = (dayOfYear - 1 + relDowJan1) / 7; // 0..53
  1358. if ((7 - relDowJan1) >= getMinimalDaysInFirstWeek()) {
  1359. ++woy;
  1360. }
  1361. // XXX: The calculation of dayOfYear does not take into account
  1362. // Gregorian cut over date. The next if statement depends on that
  1363. // assumption.
  1364. if (dayOfYear > 359) { // Fast check which eliminates most cases
  1365. // Check to see if we are in the last week; if so, we need
  1366. // to handle the case in which we are the first week of the
  1367. // next year.
  1368. int lastDoy = yearLength();
  1369. int lastRelDow = (relDow + lastDoy - dayOfYear) % 7;
  1370. if (lastRelDow < 0) {
  1371. lastRelDow += 7;
  1372. }
  1373. if (((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) &&
  1374. ((dayOfYear + 7 - relDow) > lastDoy)) {
  1375. woy = 1;
  1376. }
  1377. } else if (woy == 0) {
  1378. // We are the last week of the previous year.
  1379. int prevDoy = dayOfYear + yearLength(rawYear - 1);
  1380. woy = weekNumber(prevDoy, dayOfWeek);
  1381. }
  1382. internalSet(WEEK_OF_YEAR, woy);
  1383. // WEEK_OF_YEAR end
  1384. internalSet(WEEK_OF_MONTH, weekNumber(date, dayOfWeek));
  1385. internalSet(DAY_OF_WEEK_IN_MONTH, (date-1) / 7 + 1);
  1386. }
  1387. /////////////////////////////
  1388. // Fields => Time computation
  1389. /////////////////////////////
  1390. /**
  1391. * Overrides Calendar
  1392. * Converts time field values to UTC as milliseconds.
  1393. * @exception IllegalArgumentException if any fields are invalid.
  1394. */
  1395. protected void computeTime() {
  1396. if (!isLenient() && !validateFields()) {
  1397. throw new IllegalArgumentException();
  1398. }
  1399. // This function takes advantage of the fact that unset fields in
  1400. // the time field list have a value of zero.
  1401. // The year defaults to the epoch start.
  1402. int year = (stamp[YEAR] != UNSET) ? internalGet(YEAR) : EPOCH_YEAR;
  1403. // The YEAR field must always be used regardless of its SET
  1404. // state because YEAR is a mandatory field to determine the date
  1405. // and the default value (EPOCH_YEAR) may change through the
  1406. // normalization process.
  1407. int fieldMask = 1 << YEAR;
  1408. int era = AD;
  1409. if (stamp[ERA] != UNSET) {
  1410. era = internalGet(ERA);
  1411. fieldMask |= 1 << ERA;
  1412. if (era == BC) {
  1413. year = 1 - year;
  1414. } else if (era != AD) {
  1415. // Even in lenient mode we disallow ERA values other than AD & BC
  1416. throw new IllegalArgumentException("Invalid era");
  1417. }
  1418. }
  1419. int[] fieldMaskParam = { fieldMask };
  1420. // First, use the year to determine whether to use the Gregorian or the
  1421. // Julian calendar. If the year is not the year of the cutover, this
  1422. // computation will be correct. But if the year is the cutover year,
  1423. // this may be incorrect. In that case, assume the Gregorian calendar,
  1424. // make the computation, and then recompute if the resultant millis
  1425. // indicate the wrong calendar has been assumed.
  1426. // A date such as Oct. 10, 1582 does not exist in a Gregorian calendar
  1427. // with the default changeover of Oct. 15, 1582, since in such a
  1428. // calendar Oct. 4 (Julian) is followed by Oct. 15 (Gregorian). This
  1429. // algorithm will interpret such a date using the Julian calendar,
  1430. // yielding Oct. 20, 1582 (Gregorian).
  1431. boolean isGregorian = year >= gregorianCutoverYear;
  1432. long julianDay = computeJulianDay(isGregorian, year, fieldMaskParam);
  1433. long millis = julianDayToMillis(julianDay);
  1434. // The following check handles portions of the cutover year BEFORE the
  1435. // cutover itself happens. The check for the julianDate number is for a
  1436. // rare case; it's a hard-coded number, but it's efficient. The given
  1437. // Julian day number corresponds to Dec 3, 292269055 BC, which
  1438. // corresponds to millis near Long.MIN_VALUE. The need for the check
  1439. // arises because for extremely negative Julian day numbers, the millis
  1440. // actually overflow to be positive values. Without the check, the
  1441. // initial date is interpreted with the Gregorian calendar, even when
  1442. // the cutover doesn't warrant it.
  1443. if (isGregorian != (millis >= normalizedGregorianCutover) &&
  1444. julianDay != -106749550580L) { // See above
  1445. fieldMaskParam[0] = fieldMask;
  1446. julianDay = computeJulianDay(!isGregorian, year, fieldMaskParam);
  1447. millis = julianDayToMillis(julianDay);
  1448. }
  1449. fieldMask = fieldMaskParam[0];
  1450. // Do the time portion of the conversion.
  1451. int millisInDay = 0;
  1452. // Find the best set of fields specifying the time of day. There
  1453. // are only two possibilities here; the HOUR_OF_DAY or the
  1454. // AM_PM and the HOUR.
  1455. int hourOfDayStamp = stamp[HOUR_OF_DAY];
  1456. int hourStamp = stamp[HOUR];
  1457. int bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
  1458. // Hours
  1459. if (bestStamp != UNSET) {
  1460. if (bestStamp == hourOfDayStamp) {
  1461. // Don't normalize here; let overflow bump into the next period.
  1462. // This is consistent with how we handle other fields.
  1463. millisInDay += internalGet(HOUR_OF_DAY);
  1464. fieldMask |= 1 << HOUR_OF_DAY;
  1465. } else {
  1466. // Don't normalize here; let overflow bump into the next period.
  1467. // This is consistent with how we handle other fields.
  1468. millisInDay += internalGet(HOUR);
  1469. fieldMask |= 1 << HOUR;
  1470. // The default value of AM_PM is 0 which designates AM.
  1471. if (stamp[AM_PM] != UNSET) {
  1472. millisInDay += 12 * internalGet(AM_PM);
  1473. fieldMask |= 1 << AM_PM;
  1474. }
  1475. }
  1476. }
  1477. millisInDay *= 60;
  1478. if (stamp[MINUTE] != UNSET) {
  1479. millisInDay += internalGet(MINUTE); // now have minutes
  1480. fieldMask |= 1 << MINUTE;
  1481. }
  1482. millisInDay *= 60;
  1483. if (stamp[SECOND] != UNSET) {
  1484. millisInDay += internalGet(SECOND); // now have seconds
  1485. fieldMask |= 1 << SECOND;
  1486. }
  1487. millisInDay *= 1000;
  1488. if (stamp[MILLISECOND] != UNSET) {
  1489. millisInDay += internalGet(MILLISECOND); // now have millis
  1490. fieldMask |= 1 << MILLISECOND;
  1491. }
  1492. // Now add date and millisInDay together, to make millis contain local wall
  1493. // millis, with no zone or DST adjustments
  1494. millis += millisInDay;
  1495. // Compute the time zone offset and DST offset. There are two potential
  1496. // ambiguities here. We'll assume a 2:00 am (wall time) switchover time
  1497. // for discussion purposes here.
  1498. // 1. The transition into DST. Here, a designated time of 2:00 am - 2:59 am
  1499. // can be in standard or in DST depending. However, 2:00 am is an invalid
  1500. // representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST).
  1501. // We assume standard time.
  1502. // 2. The transition out of DST. Here, a designated time of 1:00 am - 1:59 am
  1503. // can be in standard or DST. Both are valid representations (the rep
  1504. // jumps from 1:59:59 DST to 1:00:00 Std).
  1505. // Again, we assume standard time.
  1506. // We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET
  1507. // or DST_OFFSET fields; then we use those fields.
  1508. TimeZone zone = getTimeZone();
  1509. if (zone instanceof ZoneInfo) {
  1510. int[] offsets = new int[2];
  1511. ((ZoneInfo)zone).getOffsetsByWall(millis, offsets);
  1512. int zoneOffset = 0;
  1513. if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
  1514. zoneOffset = internalGet(ZONE_OFFSET);
  1515. fieldMask |= 1 << ZONE_OFFSET;
  1516. } else {
  1517. zoneOffset = offsets[0];
  1518. }
  1519. if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
  1520. zoneOffset += internalGet(DST_OFFSET);
  1521. fieldMask |= 1 << DST_OFFSET;
  1522. } else {
  1523. zoneOffset += offsets[1];
  1524. }
  1525. time = millis - zoneOffset;
  1526. } else {
  1527. int zoneOffset = 0;
  1528. if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
  1529. zoneOffset = internalGet(ZONE_OFFSET);
  1530. fieldMask |= 1 << ZONE_OFFSET;
  1531. } else {
  1532. zoneOffset = zone.getRawOffset();
  1533. }
  1534. if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
  1535. time = millis - (zoneOffset + internalGet(DST_OFFSET));
  1536. fieldMask |= 1 << DST_OFFSET;
  1537. } else {
  1538. time = millis - zone.getOffsets(millis - (long)zoneOffset, null);
  1539. }
  1540. }
  1541. // In lenient mode, we need to normalize the fields that have
  1542. // any SET state (i.e., not UNSET) from the time value. First,
  1543. // we calculate all field values and then discard values of
  1544. // the UNSET fields. (4685354)
  1545. if (isLenient()) {
  1546. computeFieldsImpl();
  1547. }
  1548. for (int i = 0; i < fields.length; i++) {
  1549. if (isSet(i)) {
  1550. int bitMask = 1 << i;
  1551. if ((fieldMask & bitMask) != bitMask) {
  1552. internalClear(i);
  1553. } else {
  1554. stamp[i] = INTERNALLY_SET;
  1555. isSet[i] = true;
  1556. }
  1557. }
  1558. }
  1559. }
  1560. /**
  1561. * Compute the Julian day number under either the Gregorian or the
  1562. * Julian calendar, using the given year and the remaining fields.
  1563. * @param isGregorian if true, use the Gregorian calendar
  1564. * @param year the adjusted year number, with 0 indicating the
  1565. * year 1 BC, -1 indicating 2 BC, etc.
  1566. * @param fieldMaskParam fieldMaskParam[0] is a bit mask to
  1567. * specify which fields have been used to determine the date. The
  1568. * value is updated upon return.
  1569. * @return the Julian day number
  1570. */
  1571. private final long computeJulianDay(boolean isGregorian, int year,
  1572. int[] fieldMaskParam) {
  1573. int month = 0, date = 0, y;
  1574. long millis = 0;
  1575. // bit masks to remember which fields have been used to
  1576. // determine the date
  1577. int fieldMask = fieldMaskParam[0];
  1578. // Find the most recent group of fields specifying the day within
  1579. // the year. These may be any of the following combinations:
  1580. // MONTH + DAY_OF_MONTH
  1581. // MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
  1582. // MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
  1583. // DAY_OF_YEAR
  1584. // WEEK_OF_YEAR + DAY_OF_WEEK
  1585. // We look for the most recent of the fields in each group to determine
  1586. // the age of the group. For groups involving a week-related field such
  1587. // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
  1588. // week-related field and the DAY_OF_WEEK must be set for the group as a
  1589. // whole to be considered. (See bug 4153860 - liu 7/24/98.)
  1590. int dowStamp = stamp[DAY_OF_WEEK];
  1591. int monthStamp = stamp[MONTH];
  1592. int domStamp = stamp[DAY_OF_MONTH];
  1593. int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
  1594. int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
  1595. int doyStamp = stamp[DAY_OF_YEAR];
  1596. int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
  1597. int bestStamp = domStamp;
  1598. if (womStamp > bestStamp) {
  1599. bestStamp = womStamp;
  1600. }
  1601. if (dowimStamp > bestStamp) {
  1602. bestStamp = dowimStamp;
  1603. }
  1604. if (doyStamp > bestStamp) {
  1605. bestStamp = doyStamp;
  1606. }
  1607. if (woyStamp > bestStamp) {
  1608. bestStamp = woyStamp;
  1609. }
  1610. /* No complete combination exists. Look for WEEK_OF_MONTH,
  1611. * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone. Treat DAY_OF_WEEK alone
  1612. * as DAY_OF_WEEK_IN_MONTH.
  1613. */
  1614. if (bestStamp == UNSET) {
  1615. womStamp = stamp[WEEK_OF_MONTH];
  1616. dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
  1617. woyStamp = stamp[WEEK_OF_YEAR];
  1618. bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);
  1619. /* Treat MONTH alone or no fields at all as DAY_OF_MONTH. This may
  1620. * result in bestStamp = domStamp = UNSET if no fields are set,
  1621. * which indicates DAY_OF_MONTH.
  1622. */
  1623. if (bestStamp == UNSET) {
  1624. bestStamp = domStamp = monthStamp;
  1625. }
  1626. }
  1627. boolean useMonth = false;
  1628. if (bestStamp == domStamp ||
  1629. (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||
  1630. (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {
  1631. useMonth = true;
  1632. // We have the month specified. Make it 0-based for the algorithm.
  1633. month = (monthStamp != UNSET) ? internalGet(MONTH) - JANUARY : 0;
  1634. // If the month is out of range, adjust it into range
  1635. if (month < 0 || month > 11) {
  1636. int[] rem = new int[1];
  1637. year += floorDivide(month, 12, rem);
  1638. month = rem[0];
  1639. }
  1640. // Set the MONTH field mask because it's been determined
  1641. // to use the MONTH field.
  1642. fieldMask |= 1 << MONTH;
  1643. }
  1644. boolean isLeap = year%4 == 0;
  1645. y = year - 1;
  1646. long julianDay = 365L*y + floorDivide(y, 4) + (JAN_1_1_JULIAN_DAY - 3);
  1647. if (isGregorian) {
  1648. isLeap = isLeap && ((year%100 != 0) || (year%400 == 0));
  1649. // Add 2 because Gregorian calendar starts 2 days after Julian calendar
  1650. julianDay += floorDivide(y, 400) - floorDivide(y, 100) + 2;
  1651. }
  1652. // At this point julianDay is the 0-based day BEFORE the first day of
  1653. // January 1, year 1 of the given calendar. If julianDay == 0, it
  1654. // specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
  1655. // or Gregorian).
  1656. if (useMonth) {
  1657. julianDay += isLeap ? LEAP_NUM_DAYS[month] : NUM_DAYS[month];
  1658. if (bestStamp == domStamp) {
  1659. if (stamp[DAY_OF_MONTH] != UNSET) {
  1660. date = internalGet(DAY_OF_MONTH);
  1661. fieldMask |= 1 << DAY_OF_MONTH;
  1662. } else {
  1663. date = 1;
  1664. }
  1665. } else { // assert(bestStamp == womStamp || bestStamp == dowimStamp)
  1666. // Compute from day of week plus week number or from the day of
  1667. // week plus the day of week in month. The computations are
  1668. // almost identical.
  1669. // Find the day of the week for the first of this month. This
  1670. // is zero-based, with 0 being the locale-specific first day of
  1671. // the week. Add 1 to get the 1st day of month. Subtract
  1672. // getFirstDayOfWeek() to make 0-based.
  1673. int fdm = julianDayToDayOfWeek(julianDay + 1) - getFirstDayOfWeek();
  1674. if (fdm < 0) {
  1675. fdm += 7;
  1676. }
  1677. // Find the start of the first week. This will be a date from
  1678. // 0..6. It represents the locale-specific first day of the
  1679. // week of the first day of the month, ignoring minimal days in
  1680. // first week.
  1681. int normalizedDayOfWeek = 0;
  1682. if (dowStamp != UNSET) {
  1683. normalizedDayOfWeek = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
  1684. if (normalizedDayOfWeek < 0) {
  1685. normalizedDayOfWeek += 7;
  1686. }
  1687. fieldMask |= 1 << DAY_OF_WEEK;
  1688. }
  1689. date = 1 - fdm + normalizedDayOfWeek;
  1690. if (bestStamp == womStamp) {
  1691. // Adjust for minimal days in first week.
  1692. if ((7 - fdm) < getMinimalDaysInFirstWeek()) {
  1693. date += 7;
  1694. }
  1695. // Now adjust for the week number.
  1696. date += 7 * (internalGet(WEEK_OF_MONTH) - 1);
  1697. fieldMask |= 1 << WEEK_OF_MONTH;
  1698. }
  1699. else { // assert(bestStamp == dowimStamp)
  1700. // Adjust into the month, if needed.
  1701. if (date < 1) {
  1702. date += 7;
  1703. }
  1704. // We are basing this on the day-of-week-in-month. The only
  1705. // trickiness occurs if the day-of-week-in-month is
  1706. // negative.
  1707. int dim;
  1708. if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {
  1709. dim = internalGet(DAY_OF_WEEK_IN_MONTH);
  1710. fieldMask |= 1 << DAY_OF_WEEK_IN_MONTH;
  1711. } else {
  1712. dim = 1;
  1713. }
  1714. if (dim >= 0) {
  1715. date += 7*(dim - 1);
  1716. } else {
  1717. // Move date to the last of this day-of-week in this
  1718. // month, then back up as needed. If dim==-1, we don't
  1719. // back up at all. If dim==-2, we back up once, etc.
  1720. // Don't back up past the first of the given day-of-week
  1721. // in this month. Note that we handle -2, -3,
  1722. // etc. correctly, even though values < -1 are
  1723. // technically disallowed.
  1724. date += ((monthLength(month, year) - date) / 7 + dim + 1) * 7;
  1725. }
  1726. }
  1727. }
  1728. julianDay += date;
  1729. }
  1730. else {
  1731. // assert(bestStamp == doyStamp || bestStamp == woyStamp ||
  1732. // bestStamp == UNSET). In the last case we should use January 1.
  1733. // No month, start with January 0 (day before Jan 1), then adjust.
  1734. if (bestStamp == doyStamp) {
  1735. julianDay += internalGet(DAY_OF_YEAR);
  1736. fieldMask |= 1 << DAY_OF_YEAR;
  1737. } else { // assert(bestStamp == woyStamp)
  1738. // Compute from day of week plus week of year
  1739. // Find the day of the week for the first of this year. This
  1740. // is zero-based, with 0 being the locale-specific first day of
  1741. // the week. Add 1 to get the 1st day of month. Subtract
  1742. // getFirstDayOfWeek() to make 0-based.
  1743. int fdy = julianDayToDayOfWeek(julianDay + 1) - getFirstDayOfWeek();
  1744. if (fdy < 0) {
  1745. fdy += 7;
  1746. }
  1747. // Find the start of the first week. This may be a valid date
  1748. // from -5..7. It represents the locale-specific first day of
  1749. // the week of the first day of the year.
  1750. int normalizedDayOfWeek = 0;
  1751. if (dowStamp != UNSET) {
  1752. normalizedDayOfWeek = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
  1753. if (normalizedDayOfWeek < 0) {
  1754. normalizedDayOfWeek += 7;
  1755. }
  1756. fieldMask |= 1 << DAY_OF_WEEK;
  1757. }
  1758. date = 1 - fdy + normalizedDayOfWeek;
  1759. // Adjust for minimal days in first week.
  1760. if ((7 - fdy) < getMinimalDaysInFirstWeek()) {
  1761. date += 7;
  1762. }
  1763. // Now adjust for the week number.
  1764. date += 7 * (internalGet(WEEK_OF_YEAR) - 1);
  1765. fieldMask |= 1 << WEEK_OF_YEAR;
  1766. julianDay += date;
  1767. }
  1768. }
  1769. fieldMaskParam[0] = fieldMask;
  1770. return julianDay;
  1771. }
  1772. /////////////////
  1773. // Implementation
  1774. /////////////////
  1775. /**
  1776. * Converts time as milliseconds to Julian day.
  1777. * @param millis the given milliseconds.
  1778. * @return the Julian day number.
  1779. */
  1780. private static final long millisToJulianDay(long millis) {
  1781. return EPOCH_JULIAN_DAY + floorDivide(millis, ONE_DAY);
  1782. }
  1783. /**
  1784. * Converts Julian day to time as milliseconds.
  1785. * @param julian the given Julian day number.
  1786. * @return time as milliseconds.
  1787. */
  1788. private static final long julianDayToMillis(long julian) {
  1789. return (julian - EPOCH_JULIAN_DAY) * ONE_DAY;
  1790. }
  1791. private static final int julianDayToDayOfWeek(long julian) {
  1792. // If julian is negative, then julian%7 will be negative, so we adjust
  1793. // accordingly. We add 1 because Julian day 0 is Monday.
  1794. int dayOfWeek = (int)((julian + 1) % 7);
  1795. return dayOfWeek + ((dayOfWeek < 0) ? (7 + SUNDAY) : SUNDAY);
  1796. }
  1797. /**
  1798. * Divide two long integers, returning the floor of the quotient.
  1799. * <p>
  1800. * Unlike the built-in division, this is mathematically well-behaved.
  1801. * E.g., <code>-1/4</code> => 0
  1802. * but <code>floorDivide(-1,4)</code> => -1.
  1803. * @param numerator the numerator
  1804. * @param denominator a divisor which must be > 0
  1805. * @return the floor of the quotient.
  1806. */
  1807. private static final long floorDivide(long numerator, long denominator) {
  1808. // We do this computation in order to handle
  1809. // a numerator of Long.MIN_VALUE correctly
  1810. return (numerator >= 0) ?
  1811. numerator / denominator :
  1812. ((numerator + 1) / denominator) - 1;
  1813. }
  1814. /**
  1815. * Divide two integers, returning the floor of the quotient.
  1816. * <p>
  1817. * Unlike the built-in division, this is mathematically well-behaved.
  1818. * E.g., <code>-1/4</code> => 0
  1819. * but <code>floorDivide(-1,4)</code> => -1.
  1820. * @param numerator the numerator
  1821. * @param denominator a divisor which must be > 0
  1822. * @return the floor of the quotient.
  1823. */
  1824. private static final int floorDivide(int numerator, int denominator) {
  1825. // We do this computation in order to handle
  1826. // a numerator of Integer.MIN_VALUE correctly
  1827. return (numerator >= 0) ?
  1828. numerator / denominator :
  1829. ((numerator + 1) / denominator) - 1;
  1830. }
  1831. /**
  1832. * Divide two integers, returning the floor of the quotient, and
  1833. * the modulus remainder.
  1834. * <p>
  1835. * Unlike the built-in division, this is mathematically well-behaved.
  1836. * E.g., <code>-1/4</code> => 0 and <code>-1%4</code> => -1,
  1837. * but <code>floorDivide(-1,4)</code> => -1 with <code>remainder[0]</code> => 3.
  1838. * @param numerator the numerator
  1839. * @param denominator a divisor which must be > 0
  1840. * @param remainder an array of at least one element in which the value
  1841. * <code>numerator mod denominator</code> is returned. Unlike <code>numerator
  1842. * % denominator</code>, this will always be non-negative.
  1843. * @return the floor of the quotient.
  1844. */
  1845. private static final int floorDivide(int numerator, int denominator, int[] remainder) {
  1846. if (numerator >= 0) {
  1847. remainder[0] = numerator % denominator;
  1848. return numerator / denominator;
  1849. }
  1850. int quotient = ((numerator + 1) / denominator) - 1;
  1851. remainder[0] = numerator - (quotient * denominator);
  1852. return quotient;
  1853. }
  1854. /**
  1855. * Divide two integers, returning the floor of the quotient, and
  1856. * the modulus remainder.
  1857. * <p>
  1858. * Unlike the built-in division, this is mathematically well-behaved.
  1859. * E.g., <code>-1/4</code> => 0 and <code>-1%4</code> => -1,
  1860. * but <code>floorDivide(-1,4)</code> => -1 with <code>remainder[0]</code> => 3.
  1861. * @param numerator the numerator
  1862. * @param denominator a divisor which must be > 0
  1863. * @param remainder an array of at least one element in which the value
  1864. * <code>numerator mod denominator</code> is returned. Unlike <code>numerator
  1865. * % denominator</code>, this will always be non-negative.
  1866. * @return the floor of the quotient.
  1867. */
  1868. private static final int floorDivide(long numerator, int denominator, int[] remainder) {
  1869. if (numerator >= 0) {
  1870. remainder[0] = (int)(numerator % denominator);
  1871. return (int)(numerator / denominator);
  1872. }
  1873. int quotient = (int)(((numerator + 1) / denominator) - 1);
  1874. remainder[0] = (int)(numerator - (quotient * denominator));
  1875. return quotient;
  1876. }
  1877. /**
  1878. * Return the pseudo-time-stamp for two fields, given their
  1879. * individual pseudo-time-stamps. If either of the fields
  1880. * is unset, then the aggregate is unset. Otherwise, the
  1881. * aggregate is the later of the two stamps.
  1882. */
  1883. private static final int aggregateStamp(int stamp_a, int stamp_b) {
  1884. return (stamp_a != UNSET && stamp_b != UNSET) ?
  1885. Math.max(stamp_a, stamp_b) : UNSET;
  1886. }
  1887. /**
  1888. * Return the week number of a day, within a period. This may be the week number in
  1889. * a year, or the week number in a month. Usually this will be a value >= 1, but if
  1890. * some initial days of the period are excluded from week 1, because
  1891. * minimalDaysInFirstWeek is > 1, then the week number will be zero for those
  1892. * initial days. Requires the day of week for the given date in order to determine
  1893. * the day of week of the first day of the period.
  1894. *
  1895. * @param dayOfPeriod Day-of-year or day-of-month. Should be 1 for first day of period.
  1896. * @param day Day-of-week for given dayOfPeriod. 1-based with 1=Sunday.
  1897. * @return Week number, one-based, or zero if the day falls in part of the
  1898. * month before the first week, when there are days before the first
  1899. * week because the minimum days in the first week is more than one.
  1900. */
  1901. private final int weekNumber(int dayOfPeriod, int dayOfWeek) {
  1902. // Determine the day of the week of the first day of the period
  1903. // in question (either a year or a month). Zero represents the
  1904. // first day of the week on this calendar.
  1905. int periodStartDayOfWeek = (dayOfWeek - getFirstDayOfWeek() - dayOfPeriod + 1) % 7;
  1906. if (periodStartDayOfWeek < 0) {
  1907. periodStartDayOfWeek += 7;
  1908. }
  1909. // Compute the week number. Initially, ignore the first week, which
  1910. // may be fractional (or may not be). We add periodStartDayOfWeek in
  1911. // order to fill out the first week, if it is fractional.
  1912. int weekNo = (dayOfPeriod + periodStartDayOfWeek - 1)/7;
  1913. // If the first week is long enough, then count it. If
  1914. // the minimal days in the first week is one, or if the period start
  1915. // is zero, we always increment weekNo.
  1916. if ((7 - periodStartDayOfWeek) >= getMinimalDaysInFirstWeek()) {
  1917. ++weekNo;
  1918. }
  1919. return weekNo;
  1920. }
  1921. private final int monthLength(int month, int year) {
  1922. return isLeapYear(year) ? LEAP_MONTH_LENGTH[month] : MONTH_LENGTH[month];
  1923. }
  1924. private final int monthLength(int month) {
  1925. int year = internalGet(YEAR);
  1926. if (internalGetEra() == BC) {
  1927. year = 1-year;
  1928. }
  1929. return monthLength(month, year);
  1930. }
  1931. /**
  1932. * Returns the length of the previous month. For January, returns the
  1933. * arbitrary value 31, which will not be used: This value is passed to
  1934. * SimpleTimeZone.getOffset(), and if the month is -1 (the month before
  1935. * January), the day value will be ignored.
  1936. */
  1937. private final int prevMonthLength(int month) {
  1938. return (month > 1) ? monthLength(month - 1) : 31;
  1939. }
  1940. private final int yearLength(int year) {
  1941. return isLeapYear(year) ? 366 : 365;
  1942. }
  1943. private final int yearLength() {
  1944. return isLeapYear(internalGet(YEAR)) ? 366 : 365;
  1945. }
  1946. /**
  1947. * After adjustments such as add(MONTH), add(YEAR), we don't want the
  1948. * month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar
  1949. * 3, we want it to go to Feb 28. Adjustments which might run into this
  1950. * problem call this method to retain the proper month.
  1951. */
  1952. private final void pinDayOfMonth() {
  1953. int monthLen = monthLength(internalGet(MONTH));
  1954. int dom = internalGet(DAY_OF_MONTH);
  1955. if (dom > monthLen) {
  1956. set(DAY_OF_MONTH, monthLen);
  1957. }
  1958. }
  1959. /**
  1960. * Validates the values of the set time fields.
  1961. */
  1962. private boolean validateFields() {
  1963. for (int field = 0; field < FIELD_COUNT; field++) {
  1964. // Ignore DATE and DAY_OF_YEAR which are handled below
  1965. if (field != DATE &&
  1966. field != DAY_OF_YEAR &&
  1967. isSet(field) &&
  1968. !boundsCheck(internalGet(field), field)) {
  1969. return false;
  1970. }
  1971. }
  1972. // Values differ in Least-Maximum and Maximum should be handled
  1973. // specially.
  1974. if (stamp[DATE] >= MINIMUM_USER_STAMP) {
  1975. int date = internalGet(DATE);
  1976. if (date < getMinimum(DATE) ||
  1977. date > monthLength(internalGet(MONTH))) {
  1978. return false;
  1979. }
  1980. }
  1981. if (stamp[DAY_OF_YEAR] >= MINIMUM_USER_STAMP) {
  1982. int days = internalGet(DAY_OF_YEAR);
  1983. if (days < 1 || days > yearLength()) {
  1984. return false;
  1985. }
  1986. }
  1987. // Handle DAY_OF_WEEK_IN_MONTH, which must not have the value zero.
  1988. // We've checked against minimum and maximum above already.
  1989. if (isSet(DAY_OF_WEEK_IN_MONTH) &&
  1990. 0 == internalGet(DAY_OF_WEEK_IN_MONTH)) {
  1991. return false;
  1992. }
  1993. return true;
  1994. }
  1995. /**
  1996. * Validates the value of the given time field.
  1997. */
  1998. private final boolean boundsCheck(int value, int field) {
  1999. return value >= getMinimum(field) && value <= getMaximum(field);
  2000. }
  2001. /**
  2002. * Return the day number with respect to the epoch. January 1, 1970 (Gregorian)
  2003. * is day zero.
  2004. */
  2005. private final long getEpochDay() {
  2006. complete();
  2007. // Divide by 1000 (convert to seconds) in order to prevent overflow when
  2008. // dealing with Date(Long.MIN_VALUE) and Date(Long.MAX_VALUE).
  2009. long wallSec = time1000 + (internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET))/1000;
  2010. return floorDivide(wallSec, ONE_DAY1000);
  2011. }
  2012. /**
  2013. * Return the ERA. We need a special method for this because the
  2014. * default ERA is AD, but a zero (unset) ERA is BC.
  2015. */
  2016. private final int internalGetEra() {
  2017. return isSet(ERA) ? internalGet(ERA) : AD;
  2018. }
  2019. /**
  2020. * Updates internal state.
  2021. */
  2022. private void readObject(ObjectInputStream stream)
  2023. throws IOException, ClassNotFoundException {
  2024. stream.defaultReadObject();
  2025. setGregorianChange(new Date(gregorianCutover));
  2026. }
  2027. }