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