[Go back]
[Go forward]
java/util/GregorianCalendar.java
package java.util;
public class GregorianCalendar extends Calendar {
//////////////////
// Class Variables
//////////////////
public static final int BC = 0;
public static final int AD = 1;
private static final int JAN_1_1_JULIAN_DAY = 1721426; // January 1, year 1 (Gregorian)
private static final int EPOCH_JULIAN_DAY = 2440588; // Jaunary 1, 1970 (Gregorian)
private static final int EPOCH_YEAR = 1970;
private static final int NUM_DAYS[]
= {0,31,59,90,120,151,181,212,243,273,304,334}; // 0-based, for day-in-year
private static final int LEAP_NUM_DAYS[]
= {0,31,60,91,121,152,182,213,244,274,305,335}; // 0-based, for day-in-year
private static final int MONTH_LENGTH[]
= {31,28,31,30,31,30,31,31,30,31,30,31}; // 0-based
private static final int LEAP_MONTH_LENGTH[]
= {31,29,31,30,31,30,31,31,30,31,30,31}; // 0-based
// Useful millisecond constants. Although ONE_DAY and ONE_WEEK can fit
// into ints, they must be longs in order to prevent arithmetic overflow
// when performing (bug 4173516).
private static final int ONE_SECOND = 1000;
private static final int ONE_MINUTE = 60*ONE_SECOND;
private static final int ONE_HOUR = 60*ONE_MINUTE;
private static final long ONE_DAY = 24*ONE_HOUR;
private static final long ONE_WEEK = 7*ONE_DAY;
private static final int MIN_VALUES[] = {
0,1,0,1,0,1,1,1,-1,0,0,0,0,0,0,-12*ONE_HOUR,0
};
private static final int LEAST_MAX_VALUES[] = {
1,292269054,11,52,4,28,365,7,4,1,11,23,59,59,999,12*ONE_HOUR,1*ONE_HOUR
};
private static final int MAX_VALUES[] = {
1,292278994,11,53,6,31,366,7,6,1,11,23,59,59,999,12*ONE_HOUR,1*ONE_HOUR
};
/////////////////////
// Instance Variables
/////////////////////
private long gregorianCutover = -12219292800000L;
private transient long normalizedGregorianCutover = gregorianCutover;
private transient int gregorianCutoverYear = 1582;
// Proclaim serialization compatiblity with JDK 1.1
static final long serialVersionUID = -8125100834729963327L;
///////////////
// Constructors
///////////////
public GregorianCalendar() {
this(TimeZone.getDefault(), Locale.getDefault());
}
public GregorianCalendar(TimeZone zone) {
this(zone, Locale.getDefault());
}
public GregorianCalendar(Locale aLocale) {
this(TimeZone.getDefault(), aLocale);
}
public GregorianCalendar(TimeZone zone, Locale aLocale) {
super(zone, aLocale);
setTimeInMillis(System.currentTimeMillis());
}
public GregorianCalendar(int year, int month, int date) {
super(TimeZone.getDefault(), Locale.getDefault());
this.set(ERA, AD);
this.set(YEAR, year);
this.set(MONTH, month);
this.set(DATE, date);
}
public GregorianCalendar(int year, int month, int date, int hour,
int minute) {
super(TimeZone.getDefault(), Locale.getDefault());
this.set(ERA, AD);
this.set(YEAR, year);
this.set(MONTH, month);
this.set(DATE, date);
this.set(HOUR_OF_DAY, hour);
this.set(MINUTE, minute);
}
public GregorianCalendar(int year, int month, int date, int hour,
int minute, int second) {
super(TimeZone.getDefault(), Locale.getDefault());
this.set(ERA, AD);
this.set(YEAR, year);
this.set(MONTH, month);
this.set(DATE, date);
this.set(HOUR_OF_DAY, hour);
this.set(MINUTE, minute);
this.set(SECOND, second);
}
/////////////////
// Public methods
/////////////////
public void setGregorianChange(Date date) {
gregorianCutover = date.getTime();
// Precompute two internal variables which we use to do the actual
// cutover computations. These are the normalized cutover, which is the
// midnight at or before the cutover, and the cutover year. The
// normalized cutover is in pure date milliseconds; it contains no time
// of day or timezone component, and it used to compare against other
// pure date values.
long cutoverDay = floorDivide(gregorianCutover, ONE_DAY);
normalizedGregorianCutover = cutoverDay * ONE_DAY;
// Handle the rare case of numeric overflow. If the user specifies a
// change of Date(Long.MIN_VALUE), in order to get a pure Gregorian
// calendar, then the epoch day is -106751991168, which when multiplied
// by ONE_DAY gives 9223372036794351616 -- the negative value is too
// large for 64 bits, and overflows into a positive value. We correct
// this by using the next day, which for all intents is semantically
// equivalent.
if (cutoverDay < 0 && normalizedGregorianCutover > 0) {
normalizedGregorianCutover = (cutoverDay + 1) * ONE_DAY;
}
// Normalize the year so BC values are represented as 0 and negative
// values.
GregorianCalendar cal = new GregorianCalendar(getTimeZone());
cal.setTime(date);
gregorianCutoverYear = cal.get(YEAR);
if (cal.get(ERA) == BC) gregorianCutoverYear = 1 - gregorianCutoverYear;
}
public final Date getGregorianChange() {
return new Date(gregorianCutover);
}
public boolean isLeapYear(int year) {
return year >= gregorianCutoverYear ?
((year%4 == 0) && ((year%100 != 0) || (year%400 == 0))) : // Gregorian
(year%4 == 0); // Julian
}
public boolean equals(Object obj) {
return super.equals(obj) &&
obj instanceof GregorianCalendar &&
gregorianCutover == ((GregorianCalendar)obj).gregorianCutover;
}
public int hashCode() {
return super.hashCode() ^ (int)gregorianCutover;
}
public void add(int field, int amount) {
if (amount == 0) return; // Do nothing!
complete();
if (field == YEAR) {
int year = this.internalGet(YEAR);
if (this.internalGetEra() == AD) {
year += amount;
if (year > 0)
this.set(YEAR, year);
else { // year <= 0
this.set(YEAR, 1 - year);
// if year == 0, you get 1 BC
this.set(ERA, BC);
}
}
else { // era == BC
year -= amount;
if (year > 0)
this.set(YEAR, year);
else { // year <= 0
this.set(YEAR, 1 - year);
// if year == 0, you get 1 AD
this.set(ERA, AD);
}
}
pinDayOfMonth();
}
else if (field == MONTH) {
int month = this.internalGet(MONTH) + amount;
if (month >= 0) {
set(YEAR, internalGet(YEAR) + (month / 12));
set(MONTH, (int) (month % 12));
}
else { // month < 0
set(YEAR, internalGet(YEAR) + ((month + 1) / 12) - 1);
month %= 12;
if (month < 0) month += 12;
set(MONTH, JANUARY + month);
}
pinDayOfMonth();
}
else if (field == ERA) {
int era = internalGet(ERA) + amount;
if (era < 0) era = 0;
if (era > 1) era = 1;
set(ERA, era);
}
else {
// We handle most fields here. The algorithm is to add a computed amount
// of millis to the current millis. The only wrinkle is with DST -- if
// the result of the add operation is to move from DST to Standard, or vice
// versa, we need to adjust by an hour forward or back, respectively.
// Otherwise you get weird effects in which the hour seems to shift when
// you add to the DAY_OF_MONTH field, for instance.
// We only adjust the DST for fields larger than an hour. For fields
// smaller than an hour, we cannot adjust for DST without causing problems.
// for instance, if you add one hour to April 5, 1998, 1:00 AM, in PST,
// the time becomes "2:00 AM PDT" (an illegal value), but then the adjustment
// sees the change and compensates by subtracting an hour. As a result the
// time doesn't advance at all.
long delta = amount;
boolean adjustDST = true;
switch (field) {
case WEEK_OF_YEAR:
case WEEK_OF_MONTH:
case DAY_OF_WEEK_IN_MONTH:
delta *= 7 * 24 * 60 * 60 * 1000; // 7 days
break;
case AM_PM:
delta *= 12 * 60 * 60 * 1000; // 12 hrs
break;
case DATE: // synonym of DAY_OF_MONTH
case DAY_OF_YEAR:
case DAY_OF_WEEK:
delta *= 24 * 60 * 60 * 1000; // 1 day
break;
case HOUR_OF_DAY:
case HOUR:
delta *= 60 * 60 * 1000; // 1 hour
adjustDST = false;
break;
case MINUTE:
delta *= 60 * 1000; // 1 minute
adjustDST = false;
break;
case SECOND:
delta *= 1000; // 1 second
adjustDST = false;
break;
case MILLISECOND:
adjustDST = false;
break;
case ZONE_OFFSET:
case DST_OFFSET:
default:
throw new IllegalArgumentException();
}
// Save the current DST state.
long dst = 0;
if (adjustDST) dst = internalGet(DST_OFFSET);
setTimeInMillis(time + delta); // Automatically computes fields if necessary
if (adjustDST) {
// Now do the DST adjustment alluded to above.
// Only call setTimeInMillis if necessary, because it's an expensive call.
dst -= internalGet(DST_OFFSET);
if (delta != 0) setTimeInMillis(time + dst);
}
}
}
public void roll(int field, boolean up) {
roll(field, up ? +1 : -1);
}
public void roll(int field, int amount) {
if (amount == 0) return; // Nothing to do
int min = 0, max = 0, gap;
if (field >= 0 && field < FIELD_COUNT) {
complete();
min = getMinimum(field);
max = getMaximum(field);
}
switch (field) {
case ERA:
case YEAR:
case AM_PM:
case MINUTE:
case SECOND:
case MILLISECOND:
// These fields are handled simply, since they have fixed minima
// and maxima. The field DAY_OF_MONTH is almost as simple. Other
// fields are complicated, since the range within they must roll
// varies depending on the date.
break;
case HOUR:
case HOUR_OF_DAY:
// Rolling the hour is difficult on the ONSET and CEASE days of
// daylight savings. For example, if the change occurs at
// 2 AM, we have the following progression:
// ONSET: 12 Std -> 1 Std -> 3 Dst -> 4 Dst
// CEASE: 12 Dst -> 1 Dst -> 1 Std -> 2 Std
// To get around this problem we don't use fields; we manipulate
// the time in millis directly.
{
// Assume min == 0 in calculations below
Date start = getTime();
int oldHour = internalGet(field);
int newHour = (oldHour + amount) % (max + 1);
if (newHour < 0) {
newHour += max + 1;
}
setTime(new Date(start.getTime() + ONE_HOUR * (newHour - oldHour)));
return;
}
case MONTH:
// Rolling the month involves both pinning the final value to [0, 11]
// and adjusting the DAY_OF_MONTH if necessary. We only adjust the
// DAY_OF_MONTH if, after updating the MONTH field, it is illegal.
// E.g., <jan31>.roll(MONTH, 1) -> <feb28> or <feb29>.
{
int mon = (internalGet(MONTH) + amount) % 12;
if (mon < 0) mon += 12;
set(MONTH, mon);
// Keep the day of month in range. We don't want to spill over
// into the next month; e.g., we don't want jan31 + 1 mo -> feb31 ->
// mar3.
// NOTE: We could optimize this later by checking for dom <= 28
// first. Do this if there appears to be a need. [LIU]
int monthLen = monthLength(mon);
int dom = internalGet(DAY_OF_MONTH);
if (dom > monthLen) set(DAY_OF_MONTH, monthLen);
return;
}
case WEEK_OF_YEAR:
{
// Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the
// week. Also, rolling the week of the year can have seemingly
// strange effects simply because the year of the week of year
// may be different from the calendar year. For example, the
// date Dec 28, 1997 is the first day of week 1 of 1998 (if
// weeks start on Sunday and the minimal days in first week is
// <= 3).
int woy = internalGet(WEEK_OF_YEAR);
// Get the ISO year, which matches the week of year. This
// may be one year before or after the calendar year.
int isoYear = internalGet(YEAR);
int isoDoy = internalGet(DAY_OF_YEAR);
if (internalGet(MONTH) == Calendar.JANUARY) {
if (woy >= 52) {
--isoYear;
isoDoy += yearLength(isoYear);
}
}
else {
if (woy == 1) {
isoDoy -= yearLength(isoYear);
++isoYear;
}
}
woy += amount;
// Do fast checks to avoid unnecessary computation:
if (woy < 1 || woy > 52) {
// Determine the last week of the ISO year.
// We do this using the standard formula we use
// everywhere in this file. If we can see that the
// days at the end of the year are going to fall into
// week 1 of the next year, we drop the last week by
// subtracting 7 from the last day of the year.
int lastDoy = yearLength(isoYear);
int lastRelDow = (lastDoy - isoDoy + internalGet(DAY_OF_WEEK) -
getFirstDayOfWeek()) % 7;
if (lastRelDow < 0) lastRelDow += 7;
if ((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) lastDoy -= 7;
int lastWoy = weekNumber(lastDoy, lastRelDow + 1);
woy = ((woy + lastWoy - 1) % lastWoy) + 1;
}
set(WEEK_OF_YEAR, woy);
set(YEAR, isoYear);
return;
}
case WEEK_OF_MONTH:
{
// This is tricky, because during the roll we may have to shift
// to a different day of the week. For example:
// s m t w r f s
// 1 2 3 4 5
// 6 7 8 9 10 11 12
// When rolling from the 6th or 7th back one week, we go to the
// 1st (assuming that the first partial week counts). The same
// thing happens at the end of the month.
// The other tricky thing is that we have to figure out whether
// the first partial week actually counts or not, based on the
// minimal first days in the week. And we have to use the
// correct first day of the week to delineate the week
// boundaries.
// Here's our algorithm. First, we find the real boundaries of
// the month. Then we discard the first partial week if it
// doesn't count in this locale. Then we fill in the ends with
// phantom days, so that the first partial week and the last
// partial week are full weeks. We then have a nice square
// block of weeks. We do the usual rolling within this block,
// as is done elsewhere in this method. If we wind up on one of
// the phantom days that we added, we recognize this and pin to
// the first or the last day of the month. Easy, eh?
// Normalize the DAY_OF_WEEK so that 0 is the first day of the week
// in this locale. We have dow in 0..6.
int dow = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
if (dow < 0) dow += 7;
// Find the day of the week (normalized for locale) for the first
// of the month.
int fdm = (dow - internalGet(DAY_OF_MONTH) + 1) % 7;
if (fdm < 0) fdm += 7;
// Get the first day of the first full week of the month,
// including phantom days, if any. Figure out if the first week
// counts or not; if it counts, then fill in phantom days. If
// not, advance to the first real full week (skip the partial week).
int start;
if ((7 - fdm) < getMinimalDaysInFirstWeek())
start = 8 - fdm; // Skip the first partial week
else
start = 1 - fdm; // This may be zero or negative
// Get the day of the week (normalized for locale) for the last
// day of the month.
int monthLen = monthLength(internalGet(MONTH));
int ldm = (monthLen - internalGet(DAY_OF_MONTH) + dow) % 7;
// We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here.
// Get the limit day for the blocked-off rectangular month; that
// is, the day which is one past the last day of the month,
// after the month has already been filled in with phantom days
// to fill out the last week. This day has a normalized DOW of 0.
int limit = monthLen + 7 - ldm;
// Now roll between start and (limit - 1).
gap = limit - start;
int day_of_month = (internalGet(DAY_OF_MONTH) + amount*7 -
start) % gap;
if (day_of_month < 0) day_of_month += gap;
day_of_month += start;
// Finally, pin to the real start and end of the month.
if (day_of_month < 1) day_of_month = 1;
if (day_of_month > monthLen) day_of_month = monthLen;
// Set the DAY_OF_MONTH. We rely on the fact that this field
// takes precedence over everything else (since all other fields
// are also set at this point). If this fact changes (if the
// disambiguation algorithm changes) then we will have to unset
// the appropriate fields here so that DAY_OF_MONTH is attended
// to.
set(DAY_OF_MONTH, day_of_month);
return;
}
case DAY_OF_MONTH:
max = monthLength(internalGet(MONTH));
break;
case DAY_OF_YEAR:
{
// Roll the day of year using millis. Compute the millis for
// the start of the year, and get the length of the year.
long delta = amount * ONE_DAY; // Scale up from days to millis
long min2 = time - (internalGet(DAY_OF_YEAR) - 1) * ONE_DAY;
int yearLength = yearLength();
time = (time + delta - min2) % (yearLength*ONE_DAY);
if (time < 0) time += yearLength*ONE_DAY;
setTimeInMillis(time + min2);
return;
}
case DAY_OF_WEEK:
{
// Roll the day of week using millis. Compute the millis for
// the start of the week, using the first day of week setting.
// Restrict the millis to [start, start+7days).
long delta = amount * ONE_DAY; // Scale up from days to millis
// Compute the number of days before the current day in this
// week. This will be a value 0..6.
int leadDays = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
if (leadDays < 0) leadDays += 7;
long min2 = time - leadDays * ONE_DAY;
time = (time + delta - min2) % ONE_WEEK;
if (time < 0) time += ONE_WEEK;
setTimeInMillis(time + min2);
return;
}
case DAY_OF_WEEK_IN_MONTH:
{
// Roll the day of week in the month using millis. Determine
// the first day of the week in the month, and then the last,
// and then roll within that range.
long delta = amount * ONE_WEEK; // Scale up from weeks to millis
// Find the number of same days of the week before this one
// in this month.
int preWeeks = (internalGet(DAY_OF_MONTH) - 1) / 7;
// Find the number of same days of the week after this one
// in this month.
int postWeeks = (monthLength(internalGet(MONTH)) -
internalGet(DAY_OF_MONTH)) / 7;
// From these compute the min and gap millis for rolling.
long min2 = time - preWeeks * ONE_WEEK;
long gap2 = ONE_WEEK * (preWeeks + postWeeks + 1); // Must add 1!
// Roll within this range
time = (time + delta - min2) % gap2;
if (time < 0) time += gap2;
setTimeInMillis(time + min2);
return;
}
case ZONE_OFFSET:
case DST_OFFSET:
default:
// These fields cannot be rolled
throw new IllegalArgumentException();
}
// These are the standard roll instructions. These work for all
// simple cases, that is, cases in which the limits are fixed, such
// as the hour, the month, and the era.
gap = max - min + 1;
int value = internalGet(field) + amount;
value = (value - min) % gap;
if (value < 0) value += gap;
value += min;
set(field, value);
}
public int getMinimum(int field) {
return MIN_VALUES[field];
}
public int getMaximum(int field) {
return MAX_VALUES[field];
}
public int getGreatestMinimum(int field) {
return MIN_VALUES[field];
}
public int getLeastMaximum(int field) {
return LEAST_MAX_VALUES[field];
}
public int getActualMinimum(int field) {
return getMinimum(field);
}
public int getActualMaximum(int field) {
switch (field) {
// we have functions that enable us to fast-path number of days in month
// of year
case DAY_OF_MONTH:
return monthLength(get(MONTH));
case DAY_OF_YEAR:
return yearLength();
// for week of year, week of month, or day of week in month, we
// just fall back on the default implementation in Calendar (I'm not sure
// we could do better by having special calculations here)
case WEEK_OF_YEAR:
case WEEK_OF_MONTH:
case DAY_OF_WEEK_IN_MONTH:
return super.getActualMaximum(field);
case YEAR:
{
Calendar cal = (Calendar)this.clone();
cal.setLenient(true);
int era = cal.get(ERA);
Date d = cal.getTime();
int lowGood = LEAST_MAX_VALUES[YEAR];
int highBad = MAX_VALUES[YEAR] + 1;
while ((lowGood + 1) < highBad) {
int y = (lowGood + highBad) / 2;
cal.set(YEAR, y);
if (cal.get(YEAR) == y && cal.get(ERA) == era) {
lowGood = y;
} else {
highBad = y;
cal.setTime(d); // Restore original fields
}
}
return lowGood;
}
// and we know none of the other fields have variable maxima in
// GregorianCalendar, so we can just return the fixed maximum
default:
return getMaximum(field);
}
}
//////////////////////
// Proposed public API
//////////////////////
boolean inDaylightTime() {
if (!getTimeZone().useDaylightTime()) return false;
complete(); // Force update of DST_OFFSET field
return internalGet(DST_OFFSET) != 0;
}
int getISOYear() {
complete();
int woy = internalGet(WEEK_OF_YEAR);
// Get the ISO year, which matches the week of year. This
// may be one year before or after the calendar year.
int isoYear = internalGet(YEAR);
if (internalGet(MONTH) == Calendar.JANUARY) {
if (woy >= 52) {
--isoYear;
}
}
else {
if (woy == 1) {
++isoYear;
}
}
return isoYear;
}
/////////////////////////////
// Time => Fields computation
/////////////////////////////
protected void computeFields() {
int rawOffset = getTimeZone().getRawOffset();
long localMillis = time + rawOffset;
if (time > 0 && localMillis < 0 && rawOffset > 0) {
localMillis = Long.MAX_VALUE;
} else if (time < 0 && localMillis > 0 && rawOffset < 0) {
localMillis = Long.MIN_VALUE;
}
// Time to fields takes the wall millis (Standard or DST).
timeToFields(localMillis, false);
int era = internalGetEra();
int year = internalGet(YEAR);
int month = internalGet(MONTH);
int date = internalGet(DATE);
int dayOfWeek = internalGet(DAY_OF_WEEK);
long days = (long) (localMillis / ONE_DAY);
int millisInDay = (int) (localMillis - (days * ONE_DAY));
if (millisInDay < 0) millisInDay += ONE_DAY;
// Call getOffset() to get the TimeZone offset. The millisInDay value must
// be standard local millis.
int dstOffset = getTimeZone().getOffset(era,year,month,date,dayOfWeek,millisInDay,
monthLength(month)
// 42 added to be compatible with 1.3
// 42 should be removed to correspond to 1.2
) - rawOffset;
// Adjust our millisInDay for DST, if necessary.
millisInDay += dstOffset;
// If DST has pushed us into the next day, we must call timeToFields() again.
// This happens in DST between 12:00 am and 1:00 am every day. The call to
// timeToFields() will give the wrong day, since the Standard time is in the
// previous day.
if (millisInDay >= ONE_DAY) {
long dstMillis = localMillis + dstOffset;
millisInDay -= ONE_DAY;
// As above, check for and pin extreme values
if (localMillis > 0 && dstMillis < 0 && dstOffset > 0) {
dstMillis = Long.MAX_VALUE;
} else if (localMillis < 0 && dstMillis > 0 && dstOffset < 0) {
dstMillis = Long.MIN_VALUE;
}
timeToFields(dstMillis, false);
}
// Fill in all time-related fields based on millisInDay. Call internalSet()
// so as not to perturb flags.
internalSet(MILLISECOND, millisInDay % 1000);
millisInDay /= 1000;
internalSet(SECOND, millisInDay % 60);
millisInDay /= 60;
internalSet(MINUTE, millisInDay % 60);
millisInDay /= 60;
internalSet(HOUR_OF_DAY, millisInDay);
internalSet(AM_PM, millisInDay / 12); // Assume AM == 0
internalSet(HOUR, millisInDay % 12);
internalSet(ZONE_OFFSET, rawOffset);
internalSet(DST_OFFSET, dstOffset);
// Careful here: We are manually setting the time stamps[] flags to
// INTERNALLY_SET, so we must be sure that the above code actually does
// set all these fields.
for (int i=0; i<FIELD_COUNT; ++i) {
stamp[i] = INTERNALLY_SET;
isSet[i] = true; // Remove later
}
}
private final void timeToFields(long theTime, boolean quick) {
int rawYear, year, month, date, dayOfWeek, dayOfYear, weekCount, era;
boolean isLeap;
// Compute the year, month, and day of month from the given millis
if (theTime >= normalizedGregorianCutover) {
// The Gregorian epoch day is zero for Monday January 1, year 1.
long gregorianEpochDay = millisToJulianDay(theTime) - JAN_1_1_JULIAN_DAY;
// Here we convert from the day number to the multiple radix
// representation. We use 400-year, 100-year, and 4-year cycles.
// For example, the 4-year cycle has 4 years + 1 leap day; giving
// 1461 == 365*4 + 1 days.
int[] rem = new int[1];
int n400 = floorDivide(gregorianEpochDay, 146097, rem); // 400-year cycle length
int n100 = floorDivide(rem[0], 36524, rem); // 100-year cycle length
int n4 = floorDivide(rem[0], 1461, rem); // 4-year cycle length
int n1 = floorDivide(rem[0], 365, rem);
rawYear = 400*n400 + 100*n100 + 4*n4 + n1;
dayOfYear = rem[0]; // zero-based day of year
if (n100 == 4 || n1 == 4) dayOfYear = 365; // Dec 31 at end of 4- or 400-yr cycle
else ++rawYear;
isLeap = ((rawYear&0x3) == 0) && // equiv. to (rawYear%4 == 0)
(rawYear%100 != 0 || rawYear%400 == 0);
// Gregorian day zero is a Monday
dayOfWeek = (int)((gregorianEpochDay+1) % 7);
}
else {
// The Julian epoch day (not the same as Julian Day)
// is zero on Saturday December 30, 0 (Gregorian).
long julianEpochDay = millisToJulianDay(theTime) - (JAN_1_1_JULIAN_DAY - 2);
rawYear = (int) floorDivide(4*julianEpochDay + 1464, 1461);
// Compute the Julian calendar day number for January 1, rawYear
long january1 = 365*(rawYear-1) + floorDivide(rawYear-1, 4);
dayOfYear = (int)(julianEpochDay - january1); // 0-based
// Julian leap years occurred historically every 4 years starting
// with 8 AD. Before 8 AD the spacing is irregular; every 3 years
// from 45 BC to 9 BC, and then none until 8 AD. However, we don't
// implement this historical detail; instead, we implement the
// computatinally cleaner proleptic calendar, which assumes
// consistent 4-year cycles throughout time.
isLeap = ((rawYear&0x3) == 0); // equiv. to (rawYear%4 == 0)
// Julian calendar day zero is a Saturday
dayOfWeek = (int)((julianEpochDay-1) % 7);
}
// Common Julian/Gregorian calculation
int correction = 0;
int march1 = isLeap ? 60 : 59; // zero-based DOY for March 1
if (dayOfYear >= march1) correction = isLeap ? 1 : 2;
month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month
date = dayOfYear -
(isLeap ? LEAP_NUM_DAYS[month] : NUM_DAYS[month]) + 1; // one-based DOM
// Normalize day of week
dayOfWeek += (dayOfWeek < 0) ? (SUNDAY+7) : SUNDAY;
era = AD;
year = rawYear;
if (year < 1) {
era = BC;
year = 1 - year;
}
internalSet(ERA, era);
internalSet(YEAR, year);
internalSet(MONTH, month + JANUARY); // 0-based
internalSet(DATE, date);
internalSet(DAY_OF_WEEK, dayOfWeek);
internalSet(DAY_OF_YEAR, ++dayOfYear); // Convert from 0-based to 1-based
if (quick) return;
// Compute the week of the year. Valid week numbers run from 1 to 52
// or 53, depending on the year, the first day of the week, and the
// minimal days in the first week. Days at the start of the year may
// fall into the last week of the previous year; days at the end of
// the year may fall into the first week of the next year.
int relDow = (dayOfWeek + 7 - getFirstDayOfWeek()) % 7; // 0..6
int relDowJan1 = (dayOfWeek - dayOfYear + 1 - getFirstDayOfWeek()) % 7; // -6..6
if (relDowJan1 < 0) relDowJan1 += 7; // 0..6
int woy = (dayOfYear - 1 + relDowJan1) / 7; // 0..53
if ((7 - relDowJan1) >= getMinimalDaysInFirstWeek()) {
++woy;
// Check to see if we are in the last week; if so, we need
// to handle the case in which we are the first week of the
// next year.
int lastDoy = yearLength();
int lastRelDow = (relDow + lastDoy - dayOfYear) % 7;
if (lastRelDow < 0) lastRelDow += 7;
if (dayOfYear > 359 && // Fast check which eliminates most cases
(6 - lastRelDow) >= getMinimalDaysInFirstWeek() &&
(dayOfYear + 7 - relDow) > lastDoy) woy = 1;
}
else if (woy == 0) {
// We are the last week of the previous year.
int prevDoy = dayOfYear + yearLength(rawYear - 1);
int prevDow = (dayOfWeek + 6) % 7; // 0..6; This is actually DOW-1 % 7
// The following line is unnecessary because weekNumber() will
// do any needed normalization internally.
// if (prevDow == 0) prevDow = 7; // 1..7
woy = weekNumber(prevDoy, prevDow);
}
internalSet(WEEK_OF_YEAR, woy);
internalSet(WEEK_OF_MONTH, weekNumber(date, dayOfWeek));
internalSet(DAY_OF_WEEK_IN_MONTH, (date-1) / 7 + 1);
}
/////////////////////////////
// Fields => Time computation
/////////////////////////////
protected void computeTime() {
if (!isLenient() && !validateFields())
throw new IllegalArgumentException();
// This function takes advantage of the fact that unset fields in
// the time field list have a value of zero.
// The year defaults to the epoch start.
int year = (stamp[YEAR] != UNSET) ? internalGet(YEAR) : EPOCH_YEAR;
int era = AD;
if (stamp[ERA] != UNSET) {
era = internalGet(ERA);
if (era == BC)
year = 1 - year;
// Even in lenient mode we disallow ERA values other than AD & BC
else if (era != AD)
throw new IllegalArgumentException("Invalid era");
}
// First, use the year to determine whether to use the Gregorian or the
// Julian calendar. If the year is not the year of the cutover, this
// computation will be correct. But if the year is the cutover year,
// this may be incorrect. In that case, assume the Gregorian calendar,
// make the computation, and then recompute if the resultant millis
// indicate the wrong calendar has been assumed.
// A date such as Oct. 10, 1582 does not exist in a Gregorian calendar
// with the default changeover of Oct. 15, 1582, since in such a
// calendar Oct. 4 (Julian) is followed by Oct. 15 (Gregorian). This
// algorithm will interpret such a date using the Julian calendar,
// yielding Oct. 20, 1582 (Gregorian).
boolean isGregorian = year >= gregorianCutoverYear;
long julianDay = computeJulianDay(isGregorian, year);
long millis = julianDayToMillis(julianDay);
// The following check handles portions of the cutover year BEFORE the
// cutover itself happens. The check for the julianDate number is for a
// rare case; it's a hardcoded number, but it's efficient. The given
// Julian day number corresponds to Dec 3, 292269055 BC, which
// corresponds to millis near Long.MIN_VALUE. The need for the check
// arises because for extremely negative Julian day numbers, the millis
// actually overflow to be positive values. Without the check, the
// initial date is interpreted with the Gregorian calendar, even when
// the cutover doesn't warrant it.
if (isGregorian != (millis >= normalizedGregorianCutover) &&
julianDay != -106749550580L) { // See above
julianDay = computeJulianDay(!isGregorian, year);
millis = julianDayToMillis(julianDay);
}
// Do the time portion of the conversion.
int millisInDay = 0;
// Find the best set of fields specifying the time of day. There
// are only two possibilities here; the HOUR_OF_DAY or the
// AM_PM and the HOUR.
int hourOfDayStamp = stamp[HOUR_OF_DAY];
int hourStamp = stamp[HOUR];
int bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
// Hours
if (bestStamp != UNSET) {
if (bestStamp == hourOfDayStamp)
// Don't normalize here; let overflow bump into the next period.
// This is consistent with how we handle other fields.
millisInDay += internalGet(HOUR_OF_DAY);
else {
// Don't normalize here; let overflow bump into the next period.
// This is consistent with how we handle other fields.
millisInDay += internalGet(HOUR);
millisInDay += 12 * internalGet(AM_PM); // Default works for unset AM_PM
}
}
// We use the fact that unset == 0; we start with millisInDay
// == HOUR_OF_DAY.
millisInDay *= 60;
millisInDay += internalGet(MINUTE); // now have minutes
millisInDay *= 60;
millisInDay += internalGet(SECOND); // now have seconds
millisInDay *= 1000;
millisInDay += internalGet(MILLISECOND); // now have millis
// Compute the time zone offset and DST offset. There are two potential
// ambiguities here. We'll assume a 2:00 am (wall time) switchover time
// for discussion purposes here.
// 1. The transition into DST. Here, a designated time of 2:00 am - 2:59 am
// can be in standard or in DST depending. However, 2:00 am is an invalid
// representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST).
// We assume standard time.
// 2. The transition out of DST. Here, a designated time of 1:00 am - 1:59 am
// can be in standard or DST. Both are valid representations (the rep
// jumps from 1:59:59 DST to 1:00:00 Std).
// Again, we assume standard time.
// We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET
// or DST_OFFSET fields; then we use those fields.
TimeZone zone = getTimeZone();
int zoneOffset = (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP)
?
internalGet(ZONE_OFFSET) : zone.getRawOffset();
// Now add date and millisInDay together, to make millis contain local wall
// millis, with no zone or DST adjustments
millis += millisInDay;
int dstOffset = 0;
if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP
)
dstOffset = internalGet(DST_OFFSET);
else {
int[] normalizedMillisInDay = new int[1];
floorDivide(millis, (int)ONE_DAY, normalizedMillisInDay);
// We need to have the month, the day, and the day of the week.
// Calling timeToFields will compute the MONTH and DATE fields.
// If we're lenient then we need to call timeToFields() to
// normalize the year, month, and date numbers.
int dow;
if (isLenient() || stamp[MONTH] == UNSET || stamp[DATE] == UNSET
|| millisInDay != normalizedMillisInDay[0]) {
timeToFields(millis, true); // Use wall time; true == do quick computation
dow = internalGet(DAY_OF_WEEK); // DOW is computed by timeToFields
}
else {
// It's tempting to try to use DAY_OF_WEEK here, if it
// is set, but we CAN'T. Even if it's set, it might have
// been set wrong by the user. We should rely only on
// the Julian day number, which has been computed correctly
// using the disambiguation algorithm above. [LIU]
dow = julianDayToDayOfWeek(julianDay);
}
// It's tempting to try to use DAY_OF_WEEK here, if it
// is set, but we CAN'T. Even if it's set, it might have
// been set wrong by the user. We should rely only on
// the Julian day number, which has been computed correctly
// using the disambiguation algorithm above. [LIU]
dstOffset = zone.getOffset(era,
internalGet(YEAR),
internalGet(MONTH),
internalGet(DATE),
dow,
normalizedMillisInDay[0],
// 42 added to be compatible with 1.3
// 42 should be removed to correspond to 1.2
monthLength(internalGet(MONTH))) -
zoneOffset;
// Note: Because we pass in wall millisInDay, rather than
// standard millisInDay, we interpret "1:00 am" on the day
// of cessation of DST as "1:00 am Std" (assuming the time
// of cessation is 2:00 am).
}
// Store our final computed GMT time, with timezone adjustments.
time = millis - zoneOffset - dstOffset;
}
private final long computeJulianDay(boolean isGregorian, int year) {
int month = 0, date = 0, y;
long millis = 0;
// Find the most recent group of fields specifying the day within
// the year. These may be any of the following combinations:
// MONTH + DAY_OF_MONTH
// MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
// MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
// DAY_OF_YEAR
// WEEK_OF_YEAR + DAY_OF_WEEK
// We look for the most recent of the fields in each group to determine
// the age of the group. For groups involving a week-related field such
// as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
// week-related field and the DAY_OF_WEEK must be set for the group as a
// whole to be considered. (See bug 4153860 - liu 7/24/98.)
int dowStamp = stamp[DAY_OF_WEEK];
int monthStamp = stamp[MONTH];
int domStamp = stamp[DAY_OF_MONTH];
int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
int doyStamp = stamp[DAY_OF_YEAR];
int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
int bestStamp = (monthStamp > domStamp) ? monthStamp : domStamp;
if (womStamp > bestStamp) bestStamp = womStamp;
if (dowimStamp > bestStamp) bestStamp = dowimStamp;
if (doyStamp > bestStamp) bestStamp = doyStamp;
if (woyStamp > bestStamp) bestStamp = woyStamp;
boolean useMonth = false;
if (bestStamp != UNSET &&
(bestStamp == monthStamp ||
bestStamp == domStamp ||
bestStamp == womStamp ||
bestStamp == dowimStamp)) {
useMonth = true;
// We have the month specified. Make it 0-based for the algorithm.
month = (monthStamp != UNSET) ? internalGet(MONTH) - JANUARY : 0;
// If the month is out of range, adjust it into range
if (month < 0 || month > 11) {
int[] rem = new int[1];
year += floorDivide(month, 12, rem);
month = rem[0];
}
}
boolean isLeap = year%4 == 0;
y = year - 1;
long julianDay = 365L*y + floorDivide(y, 4) + (JAN_1_1_JULIAN_DAY - 3);
if (isGregorian) {
isLeap = isLeap && ((year%100 != 0) || (year%400 == 0));
// Add 2 because Gregorian calendar starts 2 days after Julian calendar
julianDay += floorDivide(y, 400) - floorDivide(y, 100) + 2;
}
// At this point julianDay is the 0-based day BEFORE the first day of
// January 1, year 1 of the given calendar. If julianDay == 0, it
// specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
// or Gregorian).
if (useMonth) {
julianDay += isLeap ? LEAP_NUM_DAYS[month] : NUM_DAYS[month];
if (bestStamp == domStamp ||
bestStamp == monthStamp) {
date = (domStamp != UNSET) ? internalGet(DAY_OF_MONTH) : 1;
}
else { // assert(bestStamp == womStamp || bestStamp == dowimStamp)
// Compute from day of week plus week number or from the day of
// week plus the day of week in month. The computations are
// almost identical.
// Find the day of the week for the first of this month. This
// is zero-based, with 0 being the locale-specific first day of
// the week. Add 1 to get the 1st day of month. Subtract
// getFirstDayOfWeek() to make 0-based.
int fdm = julianDayToDayOfWeek(julianDay + 1) - getFirstDayOfWeek();
if (fdm < 0) fdm += 7;
// Find the start of the first week. This will be a date from
// 1..-6. It represents the locale-specific first day of the
// week of the first day of the month, ignoring minimal days in
// first week.
date = 1 - fdm + ((stamp[DAY_OF_WEEK] != UNSET) ?
(internalGet(DAY_OF_WEEK) - getFirstDayOfWeek()) : 0);
if (bestStamp == womStamp) {
// Adjust for minimal days in first week.
if ((7 - fdm) < getMinimalDaysInFirstWeek()) date += 7;
// Now adjust for the week number.
date += 7 * (internalGet(WEEK_OF_MONTH) - 1);
}
else { // assert(bestStamp == dowimStamp)
// Adjust into the month, if needed.
if (date < 1) date += 7;
// We are basing this on the day-of-week-in-month. The only
// trickiness occurs if the day-of-week-in-month is
// negative.
int dim = internalGet(DAY_OF_WEEK_IN_MONTH);
if (dim >= 0) date += 7*(dim - 1);
else {
// Move date to the last of this day-of-week in this
// month, then back up as needed. If dim==-1, we don't
// back up at all. If dim==-2, we back up once, etc.
// Don't back up past the first of the given day-of-week
// in this month. Note that we handle -2, -3,
// etc. correctly, even though values < -1 are
// technically disallowed.
date += ((monthLength(internalGet(MONTH), year) - date) / 7 + dim + 1) * 7;
}
}
}
julianDay += date;
}
else {
// assert(bestStamp == doyStamp || bestStamp == woyStamp ||
// bestStamp == UNSET). In the last case we should use January 1.
// No month, start with January 0 (day before Jan 1), then adjust.
if (bestStamp == UNSET) {
++julianDay; // Advance to January 1
}
else if (bestStamp == doyStamp) {
julianDay += internalGet(DAY_OF_YEAR);
}
else if (bestStamp == woyStamp) {
// Compute from day of week plus week of year
// Find the day of the week for the first of this year. This
// is zero-based, with 0 being the locale-specific first day of
// the week. Add 1 to get the 1st day of month. Subtract
// getFirstDayOfWeek() to make 0-based.
int fdy = julianDayToDayOfWeek(julianDay + 1) - getFirstDayOfWeek();
if (fdy < 0) fdy += 7;
// Find the start of the first week. This may be a valid date
// from 1..7, or a date before the first, from 0..-6. It
// represents the locale-specific first day of the week
// of the first day of the year.
// First ignore the minimal days in first week.
date = 1 - fdy + ((stamp[DAY_OF_WEEK] != UNSET) ?
(internalGet(DAY_OF_WEEK) - getFirstDayOfWeek()) : 0);
// Adjust for minimal days in first week.
if ((7 - fdy) < getMinimalDaysInFirstWeek()) date += 7;
// Now adjust for the week number.
date += 7 * (internalGet(WEEK_OF_YEAR) - 1);
julianDay += date;
}
}
return julianDay;
}
/////////////////
// Implementation
/////////////////
private static final long millisToJulianDay(long millis) {
return EPOCH_JULIAN_DAY + floorDivide(millis, ONE_DAY);
}
private static final long julianDayToMillis(long julian) {
return (julian - EPOCH_JULIAN_DAY) * ONE_DAY;
}
private static final int julianDayToDayOfWeek(long julian) {
// If julian is negative, then julian%7 will be negative, so we adjust
// accordingly. We add 1 because Julian day 0 is Monday.
int dayOfWeek = (int)((julian + 1) % 7);
return dayOfWeek + ((dayOfWeek < 0) ? (7 + SUNDAY) : SUNDAY);
}
private static final long floorDivide(long numerator, long denominator) {
// We do this computation in order to handle
// a numerator of Long.MIN_VALUE correctly
return (numerator >= 0) ?
numerator / denominator :
((numerator + 1) / denominator) - 1;
}
private static final int floorDivide(int numerator, int denominator) {
// We do this computation in order to handle
// a numerator of Integer.MIN_VALUE correctly
return (numerator >= 0) ?
numerator / denominator :
((numerator + 1) / denominator) - 1;
}
private static final int floorDivide(int numerator, int denominator, int[] remainder) {
if (numerator >= 0) {
remainder[0] = numerator % denominator;
return numerator / denominator;
}
int quotient = ((numerator + 1) / denominator) - 1;
remainder[0] = numerator - (quotient * denominator);
return quotient;
}
private static final int floorDivide(long numerator, int denominator, int[] remainder) {
if (numerator >= 0) {
remainder[0] = (int)(numerator % denominator);
return (int)(numerator / denominator);
}
int quotient = (int)(((numerator + 1) / denominator) - 1);
remainder[0] = (int)(numerator - (quotient * denominator));
return quotient;
}
private static final int aggregateStamp(int stamp_a, int stamp_b) {
return (stamp_a != UNSET && stamp_b != UNSET) ?
Math.max(stamp_a, stamp_b) : UNSET;
}
private final int weekNumber(int dayOfPeriod, int dayOfWeek) {
// Determine the day of the week of the first day of the period
// in question (either a year or a month). Zero represents the
// first day of the week on this calendar.
int periodStartDayOfWeek = (dayOfWeek - getFirstDayOfWeek() - dayOfPeriod + 1) % 7;
if (periodStartDayOfWeek < 0) periodStartDayOfWeek += 7;
// Compute the week number. Initially, ignore the first week, which
// may be fractional (or may not be). We add periodStartDayOfWeek in
// order to fill out the first week, if it is fractional.
int weekNo = (dayOfPeriod + periodStartDayOfWeek - 1)/7;
// If the first week is long enough, then count it. If
// the minimal days in the first week is one, or if the period start
// is zero, we always increment weekNo.
if ((7 - periodStartDayOfWeek) >= getMinimalDaysInFirstWeek()) ++weekNo;
return weekNo;
}
private final int monthLength(int month, int year) {
return isLeapYear(year) ? LEAP_MONTH_LENGTH[month] : MONTH_LENGTH[month];
}
private final int monthLength(int month) {
int year = internalGet(YEAR);
if (internalGetEra() == BC) {
year = 1-year;
}
return monthLength(month, year);
}
private final int yearLength(int year) {
return isLeapYear(year) ? 366 : 365;
}
private final int yearLength() {
return isLeapYear(internalGet(YEAR)) ? 366 : 365;
}
private final void pinDayOfMonth() {
int monthLen = monthLength(internalGet(MONTH));
int dom = internalGet(DAY_OF_MONTH);
if (dom > monthLen) set(DAY_OF_MONTH, monthLen);
}
private boolean validateFields() {
for (int field = 0; field < FIELD_COUNT; field++) {
// Ignore DATE and DAY_OF_YEAR which are handled below
if (field != DATE &&
field != DAY_OF_YEAR &&
isSet(field) &&
!boundsCheck(internalGet(field), field))
return false;
}
// Values differ in Least-Maximum and Maximum should be handled
// specially.
if (isSet(DATE)) {
int date = internalGet(DATE);
if (date < getMinimum(DATE) ||
date > monthLength(internalGet(MONTH))) {
return false;
}
}
if (isSet(DAY_OF_YEAR)) {
int days = internalGet(DAY_OF_YEAR);
if (days < 1 || days > yearLength()) return false;
}
// Handle DAY_OF_WEEK_IN_MONTH, which must not have the value zero.
// We've checked against minimum and maximum above already.
if (isSet(DAY_OF_WEEK_IN_MONTH) &&
0 == internalGet(DAY_OF_WEEK_IN_MONTH)) return false;
return true;
}
private final boolean boundsCheck(int value, int field) {
return value >= getMinimum(field) && value <= getMaximum(field);
}
private final long getEpochDay() {
complete();
// Divide by 1000 (convert to seconds) in order to prevent overflow when
// dealing with Date(Long.MIN_VALUE) and Date(Long.MAX_VALUE).
long wallSec = time/1000 + (internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET))/1000;
return floorDivide(wallSec, ONE_DAY/1000);
}
private final int internalGetEra() {
return isSet(ERA) ? internalGet(ERA) : AD;
}
}
//eof
Generated on Sun Sep 17 09:25:07 CEST 2000