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