• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 *******************************************************************************
5 * Copyright (C) 1997-2016, International Business Machines Corporation and
6 * others. All Rights Reserved.
7 *******************************************************************************
8 *
9 * File GREGOCAL.CPP
10 *
11 * Modification History:
12 *
13 *   Date        Name        Description
14 *   02/05/97    clhuang     Creation.
15 *   03/28/97    aliu        Made highly questionable fix to computeFields to
16 *                           handle DST correctly.
17 *   04/22/97    aliu        Cleaned up code drastically.  Added monthLength().
18 *                           Finished unimplemented parts of computeTime() for
19 *                           week-based date determination.  Removed quetionable
20 *                           fix and wrote correct fix for computeFields() and
21 *                           daylight time handling.  Rewrote inDaylightTime()
22 *                           and computeFields() to handle sensitive Daylight to
23 *                           Standard time transitions correctly.
24 *   05/08/97    aliu        Added code review changes.  Fixed isLeapYear() to
25 *                           not cutover.
26 *   08/12/97    aliu        Added equivalentTo.  Misc other fixes.  Updated
27 *                           add() from Java source.
28 *    07/28/98    stephen        Sync up with JDK 1.2
29 *    09/14/98    stephen        Changed type of kOneDay, kOneWeek to double.
30 *                            Fixed bug in roll()
31 *   10/15/99    aliu        Fixed j31, incorrect WEEK_OF_YEAR computation.
32 *   10/15/99    aliu        Fixed j32, cannot set date to Feb 29 2000 AD.
33 *                           {JDK bug 4210209 4209272}
34 *   11/15/99    weiv        Added YEAR_WOY and DOW_LOCAL computation
35 *                           to timeToFields method, updated kMinValues, kMaxValues & kLeastMaxValues
36 *   12/09/99    aliu        Fixed j81, calculation errors and roll bugs
37 *                           in year of cutover.
38 *   01/24/2000  aliu        Revised computeJulianDay for YEAR YEAR_WOY WOY.
39 ********************************************************************************
40 */
41 
42 #include "unicode/utypes.h"
43 #include <float.h>
44 
45 #if !UCONFIG_NO_FORMATTING
46 
47 #include "unicode/gregocal.h"
48 #include "gregoimp.h"
49 #include "umutex.h"
50 #include "uassert.h"
51 
52 // *****************************************************************************
53 // class GregorianCalendar
54 // *****************************************************************************
55 
56 /**
57 * Note that the Julian date used here is not a true Julian date, since
58 * it is measured from midnight, not noon.  This value is the Julian
59 * day number of January 1, 1970 (Gregorian calendar) at noon UTC. [LIU]
60 */
61 
62 static const int16_t kNumDays[]
63 = {0,31,59,90,120,151,181,212,243,273,304,334}; // 0-based, for day-in-year
64 static const int16_t kLeapNumDays[]
65 = {0,31,60,91,121,152,182,213,244,274,305,335}; // 0-based, for day-in-year
66 static const int8_t kMonthLength[]
67 = {31,28,31,30,31,30,31,31,30,31,30,31}; // 0-based
68 static const int8_t kLeapMonthLength[]
69 = {31,29,31,30,31,30,31,31,30,31,30,31}; // 0-based
70 
71 // setTimeInMillis() limits the Julian day range to +/-7F000000.
72 // This would seem to limit the year range to:
73 //  ms=+183882168921600000  jd=7f000000  December 20, 5828963 AD
74 //  ms=-184303902528000000  jd=81000000  September 20, 5838270 BC
75 // HOWEVER, CalendarRegressionTest/Test4167060 shows that the actual
76 // range limit on the year field is smaller (~ +/-140000). [alan 3.0]
77 
78 static const int32_t kGregorianCalendarLimits[UCAL_FIELD_COUNT][4] = {
79     // Minimum  Greatest    Least  Maximum
80     //           Minimum  Maximum
81     {        0,        0,        1,        1}, // ERA
82     {        1,        1,   140742,   144683}, // YEAR
83     {        0,        0,       11,       11}, // MONTH
84     {        1,        1,       52,       53}, // WEEK_OF_YEAR
85     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // WEEK_OF_MONTH
86     {        1,        1,       28,       31}, // DAY_OF_MONTH
87     {        1,        1,      365,      366}, // DAY_OF_YEAR
88     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK
89     {       -1,       -1,        4,        5}, // DAY_OF_WEEK_IN_MONTH
90     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM
91     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR
92     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY
93     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE
94     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND
95     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND
96     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET
97     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET
98     {  -140742,  -140742,   140742,   144683}, // YEAR_WOY
99     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL
100     {  -140742,  -140742,   140742,   144683}, // EXTENDED_YEAR
101     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY
102     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECONDS_IN_DAY
103     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // IS_LEAP_MONTH
104     {        0,        0,       11,       11}, // ORDINAL_MONTH
105 };
106 
107 /*
108 * <pre>
109 *                            Greatest       Least
110 * Field name        Minimum   Minimum     Maximum     Maximum
111 * ----------        -------   -------     -------     -------
112 * ERA                     0         0           1           1
113 * YEAR                    1         1      140742      144683
114 * MONTH                   0         0          11          11
115 * WEEK_OF_YEAR            1         1          52          53
116 * WEEK_OF_MONTH           0         0           4           6
117 * DAY_OF_MONTH            1         1          28          31
118 * DAY_OF_YEAR             1         1         365         366
119 * DAY_OF_WEEK             1         1           7           7
120 * DAY_OF_WEEK_IN_MONTH   -1        -1           4           5
121 * AM_PM                   0         0           1           1
122 * HOUR                    0         0          11          11
123 * HOUR_OF_DAY             0         0          23          23
124 * MINUTE                  0         0          59          59
125 * SECOND                  0         0          59          59
126 * MILLISECOND             0         0         999         999
127 * ZONE_OFFSET           -12*      -12*         12*         12*
128 * DST_OFFSET              0         0           1*          1*
129 * YEAR_WOY                1         1      140742      144683
130 * DOW_LOCAL               1         1           7           7
131 * </pre>
132 * (*) In units of one-hour
133 */
134 
135 #if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL)
136 #include <stdio.h>
137 #endif
138 
139 U_NAMESPACE_BEGIN
140 
141 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(GregorianCalendar)
142 
143 // 00:00:00 UTC, October 15, 1582, expressed in ms from the epoch.
144 // Note that only Italy and other Catholic countries actually
145 // observed this cutover.  Most other countries followed in
146 // the next few centuries, some as late as 1928. [LIU]
147 // in Java, -12219292800000L
148 //const UDate GregorianCalendar::kPapalCutover = -12219292800000L;
149 static const uint32_t kCutoverJulianDay = 2299161;
150 static const UDate kPapalCutover = (2299161.0 - kEpochStartAsJulianDay) * U_MILLIS_PER_DAY;
151 //static const UDate kPapalCutoverJulian = (2299161.0 - kEpochStartAsJulianDay);
152 
153 // -------------------------------------
154 
GregorianCalendar(UErrorCode & status)155 GregorianCalendar::GregorianCalendar(UErrorCode& status)
156 :   Calendar(status),
157 fGregorianCutover(kPapalCutover),
158 fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
159 fIsGregorian(true), fInvertGregorian(false)
160 {
161     setTimeInMillis(getNow(), status);
162 }
163 
164 // -------------------------------------
165 
GregorianCalendar(TimeZone * zone,UErrorCode & status)166 GregorianCalendar::GregorianCalendar(TimeZone* zone, UErrorCode& status)
167 :   Calendar(zone, Locale::getDefault(), status),
168 fGregorianCutover(kPapalCutover),
169 fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
170 fIsGregorian(true), fInvertGregorian(false)
171 {
172     setTimeInMillis(getNow(), status);
173 }
174 
175 // -------------------------------------
176 
GregorianCalendar(const TimeZone & zone,UErrorCode & status)177 GregorianCalendar::GregorianCalendar(const TimeZone& zone, UErrorCode& status)
178 :   Calendar(zone, Locale::getDefault(), status),
179 fGregorianCutover(kPapalCutover),
180 fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
181 fIsGregorian(true), fInvertGregorian(false)
182 {
183     setTimeInMillis(getNow(), status);
184 }
185 
186 // -------------------------------------
187 
GregorianCalendar(const Locale & aLocale,UErrorCode & status)188 GregorianCalendar::GregorianCalendar(const Locale& aLocale, UErrorCode& status)
189 :   Calendar(TimeZone::forLocaleOrDefault(aLocale), aLocale, status),
190 fGregorianCutover(kPapalCutover),
191 fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
192 fIsGregorian(true), fInvertGregorian(false)
193 {
194     setTimeInMillis(getNow(), status);
195 }
196 
197 // -------------------------------------
198 
GregorianCalendar(TimeZone * zone,const Locale & aLocale,UErrorCode & status)199 GregorianCalendar::GregorianCalendar(TimeZone* zone, const Locale& aLocale,
200                                      UErrorCode& status)
201                                      :   Calendar(zone, aLocale, status),
202                                      fGregorianCutover(kPapalCutover),
203                                      fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
204                                      fIsGregorian(true), fInvertGregorian(false)
205 {
206     setTimeInMillis(getNow(), status);
207 }
208 
209 // -------------------------------------
210 
GregorianCalendar(const TimeZone & zone,const Locale & aLocale,UErrorCode & status)211 GregorianCalendar::GregorianCalendar(const TimeZone& zone, const Locale& aLocale,
212                                      UErrorCode& status)
213                                      :   Calendar(zone, aLocale, status),
214                                      fGregorianCutover(kPapalCutover),
215                                      fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
216                                      fIsGregorian(true), fInvertGregorian(false)
217 {
218     setTimeInMillis(getNow(), status);
219 }
220 
221 // -------------------------------------
222 
GregorianCalendar(int32_t year,int32_t month,int32_t date,UErrorCode & status)223 GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date,
224                                      UErrorCode& status)
225                                      :   Calendar(TimeZone::createDefault(), Locale::getDefault(), status),
226                                      fGregorianCutover(kPapalCutover),
227                                      fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
228                                      fIsGregorian(true), fInvertGregorian(false)
229 {
230     set(UCAL_ERA, AD);
231     set(UCAL_YEAR, year);
232     set(UCAL_MONTH, month);
233     set(UCAL_DATE, date);
234 }
235 
236 // -------------------------------------
237 
GregorianCalendar(int32_t year,int32_t month,int32_t date,int32_t hour,int32_t minute,UErrorCode & status)238 GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date,
239                                      int32_t hour, int32_t minute, UErrorCode& status)
240                                      :   Calendar(TimeZone::createDefault(), Locale::getDefault(), status),
241                                      fGregorianCutover(kPapalCutover),
242                                      fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
243                                      fIsGregorian(true), fInvertGregorian(false)
244 {
245     set(UCAL_ERA, AD);
246     set(UCAL_YEAR, year);
247     set(UCAL_MONTH, month);
248     set(UCAL_DATE, date);
249     set(UCAL_HOUR_OF_DAY, hour);
250     set(UCAL_MINUTE, minute);
251 }
252 
253 // -------------------------------------
254 
GregorianCalendar(int32_t year,int32_t month,int32_t date,int32_t hour,int32_t minute,int32_t second,UErrorCode & status)255 GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date,
256                                      int32_t hour, int32_t minute, int32_t second,
257                                      UErrorCode& status)
258                                      :   Calendar(TimeZone::createDefault(), Locale::getDefault(), status),
259                                      fGregorianCutover(kPapalCutover),
260                                      fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
261                                      fIsGregorian(true), fInvertGregorian(false)
262 {
263     set(UCAL_ERA, AD);
264     set(UCAL_YEAR, year);
265     set(UCAL_MONTH, month);
266     set(UCAL_DATE, date);
267     set(UCAL_HOUR_OF_DAY, hour);
268     set(UCAL_MINUTE, minute);
269     set(UCAL_SECOND, second);
270 }
271 
272 // -------------------------------------
273 
~GregorianCalendar()274 GregorianCalendar::~GregorianCalendar()
275 {
276 }
277 
278 // -------------------------------------
279 
GregorianCalendar(const GregorianCalendar & source)280 GregorianCalendar::GregorianCalendar(const GregorianCalendar &source)
281 :   Calendar(source),
282 fGregorianCutover(source.fGregorianCutover),
283 fCutoverJulianDay(source.fCutoverJulianDay), fNormalizedGregorianCutover(source.fNormalizedGregorianCutover), fGregorianCutoverYear(source.fGregorianCutoverYear),
284 fIsGregorian(source.fIsGregorian), fInvertGregorian(source.fInvertGregorian)
285 {
286 }
287 
288 // -------------------------------------
289 
clone() const290 GregorianCalendar* GregorianCalendar::clone() const
291 {
292     return new GregorianCalendar(*this);
293 }
294 
295 // -------------------------------------
296 
297 GregorianCalendar &
operator =(const GregorianCalendar & right)298 GregorianCalendar::operator=(const GregorianCalendar &right)
299 {
300     if (this != &right)
301     {
302         Calendar::operator=(right);
303         fGregorianCutover = right.fGregorianCutover;
304         fNormalizedGregorianCutover = right.fNormalizedGregorianCutover;
305         fGregorianCutoverYear = right.fGregorianCutoverYear;
306         fCutoverJulianDay = right.fCutoverJulianDay;
307     }
308     return *this;
309 }
310 
311 // -------------------------------------
312 
isEquivalentTo(const Calendar & other) const313 UBool GregorianCalendar::isEquivalentTo(const Calendar& other) const
314 {
315     // Calendar override.
316     return Calendar::isEquivalentTo(other) &&
317         fGregorianCutover == ((GregorianCalendar*)&other)->fGregorianCutover;
318 }
319 
320 // -------------------------------------
321 
322 void
setGregorianChange(UDate date,UErrorCode & status)323 GregorianCalendar::setGregorianChange(UDate date, UErrorCode& status)
324 {
325     if (U_FAILURE(status))
326         return;
327 
328     // Precompute two internal variables which we use to do the actual
329     // cutover computations.  These are the normalized cutover, which is the
330     // midnight at or before the cutover, and the cutover year.  The
331     // normalized cutover is in pure date milliseconds; it contains no time
332     // of day or timezone component, and it used to compare against other
333     // pure date values.
334     double cutoverDay = ClockMath::floorDivide(date, kOneDay);
335 
336     // Handle the rare case of numeric overflow where the user specifies a time
337     // outside of INT32_MIN .. INT32_MAX number of days.
338 
339     if (cutoverDay <= INT32_MIN) {
340         cutoverDay = INT32_MIN;
341         fGregorianCutover = fNormalizedGregorianCutover = cutoverDay * kOneDay;
342     } else if (cutoverDay >= INT32_MAX) {
343         cutoverDay = INT32_MAX;
344         fGregorianCutover = fNormalizedGregorianCutover = cutoverDay * kOneDay;
345     } else {
346         fNormalizedGregorianCutover = cutoverDay * kOneDay;
347         fGregorianCutover = date;
348     }
349 
350     // Normalize the year so BC values are represented as 0 and negative
351     // values.
352     GregorianCalendar *cal = new GregorianCalendar(getTimeZone(), status);
353     /* test for nullptr */
354     if (cal == nullptr) {
355         status = U_MEMORY_ALLOCATION_ERROR;
356         return;
357     }
358     if(U_FAILURE(status)) {
359         return;
360     }
361     cal->setTime(date, status);
362     fGregorianCutoverYear = cal->get(UCAL_YEAR, status);
363     if (cal->get(UCAL_ERA, status) == BC) {
364         fGregorianCutoverYear = 1 - fGregorianCutoverYear;
365     }
366     fCutoverJulianDay = static_cast<int32_t>(cutoverDay);
367     delete cal;
368 }
369 
handleComputeFields(int32_t julianDay,UErrorCode & status)370 void GregorianCalendar::handleComputeFields(int32_t julianDay, UErrorCode& status) {
371     int32_t eyear, month, dayOfMonth, dayOfYear, unusedRemainder;
372 
373     if(U_FAILURE(status)) {
374         return;
375     }
376 
377 #if defined (U_DEBUG_CAL)
378     fprintf(stderr, "%s:%d: jd%d- (greg's %d)- [cut=%d]\n",
379         __FILE__, __LINE__, julianDay, getGregorianDayOfYear(), fCutoverJulianDay);
380 #endif
381 
382     if (julianDay >= fCutoverJulianDay) {
383         month = getGregorianMonth();
384         dayOfMonth = getGregorianDayOfMonth();
385         dayOfYear = getGregorianDayOfYear();
386         eyear = getGregorianYear();
387     } else {
388         // The Julian epoch day (not the same as Julian Day)
389         // is zero on Saturday December 30, 0 (Gregorian).
390         int32_t julianEpochDay = julianDay - (kJan1_1JulianDay - 2);
391 		eyear = static_cast<int32_t>(ClockMath::floorDivide((4.0 * julianEpochDay) + 1464.0, static_cast<int32_t>(1461), &unusedRemainder));
392 
393         // Compute the Julian calendar day number for January 1, eyear
394         int32_t january1 = 365 * (eyear - 1) + ClockMath::floorDivide(eyear - 1, static_cast<int32_t>(4));
395         dayOfYear = (julianEpochDay - january1); // 0-based
396 
397         // Julian leap years occurred historically every 4 years starting
398         // with 8 AD.  Before 8 AD the spacing is irregular; every 3 years
399         // from 45 BC to 9 BC, and then none until 8 AD.  However, we don't
400         // implement this historical detail; instead, we implement the
401         // computationally cleaner proleptic calendar, which assumes
402         // consistent 4-year cycles throughout time.
403         UBool isLeap = ((eyear&0x3) == 0); // equiv. to (eyear%4 == 0)
404 
405         // Common Julian/Gregorian calculation
406         int32_t correction = 0;
407         int32_t march1 = isLeap ? 60 : 59; // zero-based DOY for March 1
408         if (dayOfYear >= march1) {
409             correction = isLeap ? 1 : 2;
410         }
411         month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month
412         dayOfMonth = dayOfYear - (isLeap?kLeapNumDays[month]:kNumDays[month]) + 1; // one-based DOM
413         ++dayOfYear;
414 #if defined (U_DEBUG_CAL)
415         //     fprintf(stderr, "%d - %d[%d] + 1\n", dayOfYear, isLeap?kLeapNumDays[month]:kNumDays[month], month );
416         //           fprintf(stderr, "%s:%d:  greg's HCF %d -> %d/%d/%d not %d/%d/%d\n",
417         //                   __FILE__, __LINE__,julianDay,
418         //          eyear,month,dayOfMonth,
419         //          getGregorianYear(), getGregorianMonth(), getGregorianDayOfMonth()  );
420         fprintf(stderr, "%s:%d: doy %d (greg's %d)- [cut=%d]\n",
421             __FILE__, __LINE__, dayOfYear, getGregorianDayOfYear(), fCutoverJulianDay);
422 #endif
423 
424     }
425 
426     // [j81] if we are after the cutover in its year, shift the day of the year
427     if((eyear == fGregorianCutoverYear) && (julianDay >= fCutoverJulianDay)) {
428         //from handleComputeMonthStart
429         int32_t gregShift = Grego::gregorianShift(eyear);
430 #if defined (U_DEBUG_CAL)
431         fprintf(stderr, "%s:%d:  gregorian shift %d :::  doy%d => %d [cut=%d]\n",
432             __FILE__, __LINE__,gregShift, dayOfYear, dayOfYear+gregShift, fCutoverJulianDay);
433 #endif
434         dayOfYear += gregShift;
435     }
436 
437     internalSet(UCAL_MONTH, month);
438     internalSet(UCAL_ORDINAL_MONTH, month);
439     internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);
440     internalSet(UCAL_DAY_OF_YEAR, dayOfYear);
441     internalSet(UCAL_EXTENDED_YEAR, eyear);
442     int32_t era = AD;
443     if (eyear < 1) {
444         era = BC;
445         eyear = 1 - eyear;
446     }
447     internalSet(UCAL_ERA, era);
448     internalSet(UCAL_YEAR, eyear);
449 }
450 
451 
452 // -------------------------------------
453 
454 UDate
getGregorianChange() const455 GregorianCalendar::getGregorianChange() const
456 {
457     return fGregorianCutover;
458 }
459 
460 // -------------------------------------
461 
462 UBool
isLeapYear(int32_t year) const463 GregorianCalendar::isLeapYear(int32_t year) const
464 {
465     // MSVC complains bitterly if we try to use Grego::isLeapYear here
466     // NOTE: year&0x3 == year%4
467     return (year >= fGregorianCutoverYear ?
468         (((year&0x3) == 0) && ((year%100 != 0) || (year%400 == 0))) : // Gregorian
469     ((year&0x3) == 0)); // Julian
470 }
471 
472 // -------------------------------------
473 
handleComputeJulianDay(UCalendarDateFields bestField,UErrorCode & status)474 int32_t GregorianCalendar::handleComputeJulianDay(UCalendarDateFields bestField, UErrorCode& status)
475 {
476     fInvertGregorian = false;
477 
478     int32_t jd = Calendar::handleComputeJulianDay(bestField, status);
479     if (U_FAILURE(status)) {
480         return 0;
481     }
482 
483     if((bestField == UCAL_WEEK_OF_YEAR) &&  // if we are doing WOY calculations, we are counting relative to Jan 1 *julian*
484         (internalGet(UCAL_EXTENDED_YEAR)==fGregorianCutoverYear) &&
485         jd >= fCutoverJulianDay) {
486             fInvertGregorian = true;  // So that the Julian Jan 1 will be used in handleComputeMonthStart
487             return Calendar::handleComputeJulianDay(bestField, status);
488         }
489 
490 
491         // The following check handles portions of the cutover year BEFORE the
492         // cutover itself happens.
493         //if ((fIsGregorian==true) != (jd >= fCutoverJulianDay)) {  /*  cutoverJulianDay)) { */
494         if ((fIsGregorian) != (jd >= fCutoverJulianDay)) {  /*  cutoverJulianDay)) { */
495 #if defined (U_DEBUG_CAL)
496             fprintf(stderr, "%s:%d: jd [invert] %d\n",
497                 __FILE__, __LINE__, jd);
498 #endif
499             fInvertGregorian = true;
500             jd = Calendar::handleComputeJulianDay(bestField, status);
501             if (U_FAILURE(status)) {
502                 return 0;
503             }
504 #if defined (U_DEBUG_CAL)
505             fprintf(stderr, "%s:%d:  fIsGregorian %s, fInvertGregorian %s - ",
506                 __FILE__, __LINE__,fIsGregorian?"T":"F", fInvertGregorian?"T":"F");
507             fprintf(stderr, " jd NOW %d\n",
508                 jd);
509 #endif
510         } else {
511 #if defined (U_DEBUG_CAL)
512             fprintf(stderr, "%s:%d: jd [==] %d - %sfIsGregorian %sfInvertGregorian, %d\n",
513                 __FILE__, __LINE__, jd, fIsGregorian?"T":"F", fInvertGregorian?"T":"F", bestField);
514 #endif
515         }
516 
517         if(fIsGregorian && (internalGet(UCAL_EXTENDED_YEAR) == fGregorianCutoverYear)) {
518             int32_t gregShift = Grego::gregorianShift(internalGet(UCAL_EXTENDED_YEAR));
519             if (bestField == UCAL_DAY_OF_YEAR) {
520 #if defined (U_DEBUG_CAL)
521                 fprintf(stderr, "%s:%d: [DOY%d] gregorian shift of JD %d += %d\n",
522                     __FILE__, __LINE__, fFields[bestField],jd, gregShift);
523 #endif
524                 jd -= gregShift;
525             } else if ( bestField == UCAL_WEEK_OF_MONTH ) {
526                 int32_t weekShift = 14;
527 #if defined (U_DEBUG_CAL)
528                 fprintf(stderr, "%s:%d: [WOY/WOM] gregorian week shift of %d += %d\n",
529                     __FILE__, __LINE__, jd, weekShift);
530 #endif
531                 jd += weekShift; // shift by weeks for week based fields.
532             }
533         }
534 
535         return jd;
536 }
537 
handleComputeMonthStart(int32_t eyear,int32_t month,UBool,UErrorCode & status) const538 int64_t GregorianCalendar::handleComputeMonthStart(int32_t eyear, int32_t month,
539 
540                                                    UBool /* useMonth */, UErrorCode& status) const
541 {
542     if (U_FAILURE(status)) {
543         return 0;
544     }
545     GregorianCalendar* nonConstThis = const_cast<GregorianCalendar*>(this); // cast away const
546 
547     // If the month is out of range, adjust it into range, and
548     // modify the extended year value accordingly.
549     if (month < 0 || month > 11) {
550         if (uprv_add32_overflow(ClockMath::floorDivide(month, 12, &month),
551                                 eyear, &eyear)) {
552             status = U_ILLEGAL_ARGUMENT_ERROR;
553             return 0;
554         }
555     }
556 
557     UBool isLeap = eyear%4 == 0;
558     int64_t y = static_cast<int64_t>(eyear) - 1;
559     int64_t julianDay = 365LL * y +
560         ClockMath::floorDivideInt64(y, 4LL) + kJan1_1JulianDay - 3LL;
561 
562     nonConstThis->fIsGregorian = (eyear >= fGregorianCutoverYear);
563 #if defined (U_DEBUG_CAL)
564     fprintf(stderr, "%s:%d: (hcms%d/%d) fIsGregorian %s, fInvertGregorian %s\n",
565         __FILE__, __LINE__, eyear,month, fIsGregorian?"T":"F", fInvertGregorian?"T":"F");
566 #endif
567     if (fInvertGregorian) {
568         nonConstThis->fIsGregorian = !fIsGregorian;
569     }
570     if (fIsGregorian) {
571         isLeap = isLeap && ((eyear%100 != 0) || (eyear%400 == 0));
572         // Add 2 because Gregorian calendar starts 2 days after
573         // Julian calendar
574         int32_t gregShift = Grego::gregorianShift(eyear);
575 #if defined (U_DEBUG_CAL)
576         fprintf(stderr, "%s:%d: (hcms%d/%d) gregorian shift of %d += %d\n",
577             __FILE__, __LINE__, eyear, month, julianDay, gregShift);
578 #endif
579         julianDay += gregShift;
580     }
581 
582     // At this point julianDay indicates the day BEFORE the first
583     // day of January 1, <eyear> of either the Julian or Gregorian
584     // calendar.
585 
586     if (month != 0) {
587         julianDay += isLeap?kLeapNumDays[month]:kNumDays[month];
588     }
589 
590     return julianDay;
591 }
592 
handleGetMonthLength(int32_t extendedYear,int32_t month,UErrorCode &) const593 int32_t GregorianCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month, UErrorCode& /* status */)  const
594 {
595     // If the month is out of range, adjust it into range, and
596     // modify the extended year value accordingly.
597     if (month < 0 || month > 11) {
598         extendedYear += ClockMath::floorDivide(month, 12, &month);
599     }
600 
601     return isLeapYear(extendedYear) ? kLeapMonthLength[month] : kMonthLength[month];
602 }
603 
handleGetYearLength(int32_t eyear) const604 int32_t GregorianCalendar::handleGetYearLength(int32_t eyear) const {
605     return isLeapYear(eyear) ? 366 : 365;
606 }
607 
608 
609 int32_t
monthLength(int32_t month,UErrorCode & status) const610 GregorianCalendar::monthLength(int32_t month, UErrorCode& status) const
611 {
612     int32_t year = internalGet(UCAL_EXTENDED_YEAR);
613     return handleGetMonthLength(year, month, status);
614 }
615 
616 // -------------------------------------
617 
618 int32_t
monthLength(int32_t month,int32_t year) const619 GregorianCalendar::monthLength(int32_t month, int32_t year) const
620 {
621     return isLeapYear(year) ? kLeapMonthLength[month] : kMonthLength[month];
622 }
623 
624 // -------------------------------------
625 
626 int32_t
yearLength() const627 GregorianCalendar::yearLength() const
628 {
629     return isLeapYear(internalGet(UCAL_YEAR)) ? 366 : 365;
630 }
631 
632 // -------------------------------------
633 
634 UBool
validateFields() const635 GregorianCalendar::validateFields() const
636 {
637     for (int32_t field = 0; field < UCAL_FIELD_COUNT; field++) {
638         // Ignore DATE and DAY_OF_YEAR which are handled below
639         if (field != UCAL_DATE &&
640             field != UCAL_DAY_OF_YEAR &&
641             isSet(static_cast<UCalendarDateFields>(field)) &&
642             !boundsCheck(internalGet(static_cast<UCalendarDateFields>(field)), static_cast<UCalendarDateFields>(field)))
643             return false;
644     }
645 
646     // Values differ in Least-Maximum and Maximum should be handled
647     // specially.
648     if (isSet(UCAL_DATE)) {
649         int32_t date = internalGet(UCAL_DATE);
650         UErrorCode internalStatus = U_ZERO_ERROR;
651         if (date < getMinimum(UCAL_DATE) ||
652             date > monthLength(internalGetMonth(internalStatus), internalStatus) ||
653             U_FAILURE(internalStatus)) {
654                 return false;
655         }
656     }
657 
658     if (isSet(UCAL_DAY_OF_YEAR)) {
659         int32_t days = internalGet(UCAL_DAY_OF_YEAR);
660         if (days < 1 || days > yearLength()) {
661             return false;
662         }
663     }
664 
665     // Handle DAY_OF_WEEK_IN_MONTH, which must not have the value zero.
666     // We've checked against minimum and maximum above already.
667     if (isSet(UCAL_DAY_OF_WEEK_IN_MONTH) &&
668         0 == internalGet(UCAL_DAY_OF_WEEK_IN_MONTH)) {
669             return false;
670         }
671 
672         return true;
673 }
674 
675 // -------------------------------------
676 
677 UBool
boundsCheck(int32_t value,UCalendarDateFields field) const678 GregorianCalendar::boundsCheck(int32_t value, UCalendarDateFields field) const
679 {
680     return value >= getMinimum(field) && value <= getMaximum(field);
681 }
682 
683 // -------------------------------------
684 
685 UDate
getEpochDay(UErrorCode & status)686 GregorianCalendar::getEpochDay(UErrorCode& status)
687 {
688     complete(status);
689     // Divide by 1000 (convert to seconds) in order to prevent overflow when
690     // dealing with UDate(Long.MIN_VALUE) and UDate(Long.MAX_VALUE).
691     double wallSec = internalGetTime()/1000 + (internalGet(UCAL_ZONE_OFFSET) + internalGet(UCAL_DST_OFFSET))/1000;
692 
693     return ClockMath::floorDivide(wallSec, kOneDay/1000.0);
694 }
695 
696 // -------------------------------------
697 
698 
699 // -------------------------------------
700 
701 /**
702 * Compute the julian day number of the day BEFORE the first day of
703 * January 1, year 1 of the given calendar.  If julianDay == 0, it
704 * specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
705 * or Gregorian).
706 */
computeJulianDayOfYear(UBool isGregorian,int32_t year,UBool & isLeap)707 double GregorianCalendar::computeJulianDayOfYear(UBool isGregorian,
708                                                  int32_t year, UBool& isLeap)
709 {
710     isLeap = year%4 == 0;
711     int32_t y = year - 1;
712     double julianDay = 365.0*y + ClockMath::floorDivide(y, 4) + (kJan1_1JulianDay - 3);
713 
714     if (isGregorian) {
715         isLeap = isLeap && ((year%100 != 0) || (year%400 == 0));
716         // Add 2 because Gregorian calendar starts 2 days after Julian calendar
717         julianDay += Grego::gregorianShift(year);
718     }
719 
720     return julianDay;
721 }
722 
723 // /**
724 //  * Compute the day of week, relative to the first day of week, from
725 //  * 0..6, of the current DOW_LOCAL or DAY_OF_WEEK fields.  This is
726 //  * equivalent to get(DOW_LOCAL) - 1.
727 //  */
728 // int32_t GregorianCalendar::computeRelativeDOW() const {
729 //     int32_t relDow = 0;
730 //     if (fStamp[UCAL_DOW_LOCAL] > fStamp[UCAL_DAY_OF_WEEK]) {
731 //         relDow = internalGet(UCAL_DOW_LOCAL) - 1; // 1-based
732 //     } else if (fStamp[UCAL_DAY_OF_WEEK] != kUnset) {
733 //         relDow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
734 //         if (relDow < 0) relDow += 7;
735 //     }
736 //     return relDow;
737 // }
738 
739 // /**
740 //  * Compute the day of week, relative to the first day of week,
741 //  * from 0..6 of the given julian day.
742 //  */
743 // int32_t GregorianCalendar::computeRelativeDOW(double julianDay) const {
744 //   int32_t relDow = julianDayToDayOfWeek(julianDay) - getFirstDayOfWeek();
745 //     if (relDow < 0) {
746 //         relDow += 7;
747 //     }
748 //     return relDow;
749 // }
750 
751 // /**
752 //  * Compute the DOY using the WEEK_OF_YEAR field and the julian day
753 //  * of the day BEFORE January 1 of a year (a return value from
754 //  * computeJulianDayOfYear).
755 //  */
756 // int32_t GregorianCalendar::computeDOYfromWOY(double julianDayOfYear) const {
757 //     // Compute DOY from day of week plus week of year
758 
759 //     // Find the day of the week for the first of this year.  This
760 //     // is zero-based, with 0 being the locale-specific first day of
761 //     // the week.  Add 1 to get first day of year.
762 //     int32_t fdy = computeRelativeDOW(julianDayOfYear + 1);
763 
764 //     return
765 //         // Compute doy of first (relative) DOW of WOY 1
766 //         (((7 - fdy) < getMinimalDaysInFirstWeek())
767 //          ? (8 - fdy) : (1 - fdy))
768 
769 //         // Adjust for the week number.
770 //         + (7 * (internalGet(UCAL_WEEK_OF_YEAR) - 1))
771 
772 //         // Adjust for the DOW
773 //         + computeRelativeDOW();
774 // }
775 
776 // -------------------------------------
777 
778 double
millisToJulianDay(UDate millis)779 GregorianCalendar::millisToJulianDay(UDate millis)
780 {
781     return static_cast<double>(kEpochStartAsJulianDay) + ClockMath::floorDivide(millis, kOneDay);
782 }
783 
784 // -------------------------------------
785 
786 UDate
julianDayToMillis(double julian)787 GregorianCalendar::julianDayToMillis(double julian)
788 {
789     return static_cast<UDate>((julian - kEpochStartAsJulianDay) * kOneDay);
790 }
791 
792 // -------------------------------------
793 
794 int32_t
aggregateStamp(int32_t stamp_a,int32_t stamp_b)795 GregorianCalendar::aggregateStamp(int32_t stamp_a, int32_t stamp_b)
796 {
797     return (((stamp_a != kUnset && stamp_b != kUnset)
798         ? uprv_max(stamp_a, stamp_b)
799         : static_cast<int32_t>(kUnset)));
800 }
801 
802 // -------------------------------------
803 
804 /**
805 * Roll a field by a signed amount.
806 * Note: This will be made public later. [LIU]
807 */
808 
809 void
roll(EDateFields field,int32_t amount,UErrorCode & status)810 GregorianCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) {
811     roll(static_cast<UCalendarDateFields>(field), amount, status);
812 }
813 
814 void
roll(UCalendarDateFields field,int32_t amount,UErrorCode & status)815 GregorianCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) UPRV_NO_SANITIZE_UNDEFINED {
816     if((amount == 0) || U_FAILURE(status)) {
817         return;
818     }
819 
820     // J81 processing. (gregorian cutover)
821     UBool inCutoverMonth = false;
822     int32_t cMonthLen=0; // 'c' for cutover; in days
823     int32_t cDayOfMonth=0; // no discontinuity: [0, cMonthLen)
824     double cMonthStart=0.0; // in ms
825 
826     // Common code - see if we're in the cutover month of the cutover year
827     if(get(UCAL_EXTENDED_YEAR, status) == fGregorianCutoverYear) {
828         switch (field) {
829         case UCAL_DAY_OF_MONTH:
830         case UCAL_WEEK_OF_MONTH:
831             {
832                 int32_t max = monthLength(internalGetMonth(status), status);
833                 if (U_FAILURE(status)) {
834                     return;
835                 }
836                 UDate t = internalGetTime();
837                 // We subtract 1 from the DAY_OF_MONTH to make it zero-based, and an
838                 // additional 10 if we are after the cutover. Thus the monthStart
839                 // value will be correct iff we actually are in the cutover month.
840                 cDayOfMonth = internalGet(UCAL_DAY_OF_MONTH) - ((t >= fGregorianCutover) ? 10 : 0);
841                 cMonthStart = t - ((cDayOfMonth - 1) * kOneDay);
842                 // A month containing the cutover is 10 days shorter.
843                 if ((cMonthStart < fGregorianCutover) &&
844                     (cMonthStart + (cMonthLen=(max-10))*kOneDay >= fGregorianCutover)) {
845                         inCutoverMonth = true;
846                 }
847             }
848             break;
849         default:
850             ;
851         }
852     }
853 
854     switch (field) {
855     case UCAL_WEEK_OF_YEAR: {
856         // Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the
857         // week.  Also, rolling the week of the year can have seemingly
858         // strange effects simply because the year of the week of year
859         // may be different from the calendar year.  For example, the
860         // date Dec 28, 1997 is the first day of week 1 of 1998 (if
861         // weeks start on Sunday and the minimal days in first week is
862         // <= 3).
863         int32_t woy = get(UCAL_WEEK_OF_YEAR, status);
864         // Get the ISO year, which matches the week of year.  This
865         // may be one year before or after the calendar year.
866         int32_t isoYear = get(UCAL_YEAR_WOY, status);
867         int32_t isoDoy = internalGet(UCAL_DAY_OF_YEAR);
868         int32_t month = internalGetMonth(status);
869         if (U_FAILURE(status)) {
870             return;
871         }
872         if (month == UCAL_JANUARY) {
873             if (woy >= 52) {
874                 isoDoy += handleGetYearLength(isoYear);
875             }
876         } else {
877             if (woy == 1) {
878                 isoDoy -= handleGetYearLength(isoYear - 1);
879             }
880         }
881         if (uprv_add32_overflow(woy, amount, &woy)) {
882             status = U_ILLEGAL_ARGUMENT_ERROR;
883             return;
884         }
885         // Do fast checks to avoid unnecessary computation:
886         if (woy < 1 || woy > 52) {
887             // Determine the last week of the ISO year.
888             // We do this using the standard formula we use
889             // everywhere in this file.  If we can see that the
890             // days at the end of the year are going to fall into
891             // week 1 of the next year, we drop the last week by
892             // subtracting 7 from the last day of the year.
893             int32_t lastDoy = handleGetYearLength(isoYear);
894             int32_t lastRelDow = (lastDoy - isoDoy + internalGet(UCAL_DAY_OF_WEEK) -
895                 getFirstDayOfWeek()) % 7;
896             if (lastRelDow < 0) lastRelDow += 7;
897             if ((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) lastDoy -= 7;
898             int32_t lastWoy = weekNumber(lastDoy, lastRelDow + 1);
899             woy = ((woy + lastWoy - 1) % lastWoy) + 1;
900         }
901         set(UCAL_WEEK_OF_YEAR, woy);
902         set(UCAL_YEAR_WOY,isoYear);
903         return;
904                             }
905 
906     case UCAL_DAY_OF_MONTH:
907         if( !inCutoverMonth ) {
908             Calendar::roll(field, amount, status);
909             return;
910         }
911         {
912             // [j81] 1582 special case for DOM
913             // The default computation works except when the current month
914             // contains the Gregorian cutover.  We handle this special case
915             // here.  [j81 - aliu]
916             double monthLen = cMonthLen * kOneDay;
917             double msIntoMonth = uprv_fmod(internalGetTime() - cMonthStart +
918                 amount * kOneDay, monthLen);
919             if (msIntoMonth < 0) {
920                 msIntoMonth += monthLen;
921             }
922 #if defined (U_DEBUG_CAL)
923             fprintf(stderr, "%s:%d: roll DOM %d  -> %.0lf ms  \n",
924                 __FILE__, __LINE__,amount, cMonthLen, cMonthStart+msIntoMonth);
925 #endif
926             setTimeInMillis(cMonthStart + msIntoMonth, status);
927             return;
928         }
929 
930     case UCAL_WEEK_OF_MONTH:
931         if( !inCutoverMonth ) {
932             Calendar::roll(field, amount, status);
933             return;
934         }
935         {
936 #if defined (U_DEBUG_CAL)
937             fprintf(stderr, "%s:%d: roll WOM %d ??????????????????? \n",
938                 __FILE__, __LINE__,amount);
939 #endif
940             // NOTE: following copied from  the old
941             //     GregorianCalendar::roll( WEEK_OF_MONTH )  code
942 
943             // This is tricky, because during the roll we may have to shift
944             // to a different day of the week.  For example:
945 
946             //    s  m  t  w  r  f  s
947             //          1  2  3  4  5
948             //    6  7  8  9 10 11 12
949 
950             // When rolling from the 6th or 7th back one week, we go to the
951             // 1st (assuming that the first partial week counts).  The same
952             // thing happens at the end of the month.
953 
954             // The other tricky thing is that we have to figure out whether
955             // the first partial week actually counts or not, based on the
956             // minimal first days in the week.  And we have to use the
957             // correct first day of the week to delineate the week
958             // boundaries.
959 
960             // Here's our algorithm.  First, we find the real boundaries of
961             // the month.  Then we discard the first partial week if it
962             // doesn't count in this locale.  Then we fill in the ends with
963             // phantom days, so that the first partial week and the last
964             // partial week are full weeks.  We then have a nice square
965             // block of weeks.  We do the usual rolling within this block,
966             // as is done elsewhere in this method.  If we wind up on one of
967             // the phantom days that we added, we recognize this and pin to
968             // the first or the last day of the month.  Easy, eh?
969 
970             // Another wrinkle: To fix jitterbug 81, we have to make all this
971             // work in the oddball month containing the Gregorian cutover.
972             // This month is 10 days shorter than usual, and also contains
973             // a discontinuity in the days; e.g., the default cutover month
974             // is Oct 1582, and goes from day of month 4 to day of month 15.
975 
976             // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
977             // in this locale.  We have dow in 0..6.
978             int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
979             if (dow < 0)
980                 dow += 7;
981 
982             // Find the day of month, compensating for cutover discontinuity.
983             int32_t dom = cDayOfMonth;
984 
985             // Find the day of the week (normalized for locale) for the first
986             // of the month.
987             int32_t fdm = (dow - dom + 1) % 7;
988             if (fdm < 0)
989                 fdm += 7;
990 
991             // Get the first day of the first full week of the month,
992             // including phantom days, if any.  Figure out if the first week
993             // counts or not; if it counts, then fill in phantom days.  If
994             // not, advance to the first real full week (skip the partial week).
995             int32_t start;
996             if ((7 - fdm) < getMinimalDaysInFirstWeek())
997                 start = 8 - fdm; // Skip the first partial week
998             else
999                 start = 1 - fdm; // This may be zero or negative
1000 
1001             // Get the day of the week (normalized for locale) for the last
1002             // day of the month.
1003             int32_t monthLen = cMonthLen;
1004             int32_t ldm = (monthLen - dom + dow) % 7;
1005             // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here.
1006 
1007             // Get the limit day for the blocked-off rectangular month; that
1008             // is, the day which is one past the last day of the month,
1009             // after the month has already been filled in with phantom days
1010             // to fill out the last week.  This day has a normalized DOW of 0.
1011             int32_t limit = monthLen + 7 - ldm;
1012 
1013             // Now roll between start and (limit - 1).
1014             int32_t gap = limit - start;
1015             int32_t newDom = (dom + amount*7 - start) % gap;
1016             if (newDom < 0)
1017                 newDom += gap;
1018             newDom += start;
1019 
1020             // Finally, pin to the real start and end of the month.
1021             if (newDom < 1)
1022                 newDom = 1;
1023             if (newDom > monthLen)
1024                 newDom = monthLen;
1025 
1026             // Set the DAY_OF_MONTH.  We rely on the fact that this field
1027             // takes precedence over everything else (since all other fields
1028             // are also set at this point).  If this fact changes (if the
1029             // disambiguation algorithm changes) then we will have to unset
1030             // the appropriate fields here so that DAY_OF_MONTH is attended
1031             // to.
1032 
1033             // If we are in the cutover month, manipulate ms directly.  Don't do
1034             // this in general because it doesn't work across DST boundaries
1035             // (details, details).  This takes care of the discontinuity.
1036             setTimeInMillis(cMonthStart + (newDom-1)*kOneDay, status);
1037             return;
1038         }
1039 
1040     default:
1041         Calendar::roll(field, amount, status);
1042         return;
1043     }
1044 }
1045 
1046 // -------------------------------------
1047 
1048 
1049 /**
1050 * Return the minimum value that this field could have, given the current date.
1051 * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
1052 * @param field    the time field.
1053 * @return         the minimum value that this field could have, given the current date.
1054 * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead.
1055 */
getActualMinimum(EDateFields field) const1056 int32_t GregorianCalendar::getActualMinimum(EDateFields field) const
1057 {
1058     return getMinimum(static_cast<UCalendarDateFields>(field));
1059 }
1060 
getActualMinimum(EDateFields field,UErrorCode &) const1061 int32_t GregorianCalendar::getActualMinimum(EDateFields field, UErrorCode& /* status */) const
1062 {
1063     return getMinimum(static_cast<UCalendarDateFields>(field));
1064 }
1065 
1066 /**
1067 * Return the minimum value that this field could have, given the current date.
1068 * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
1069 * @param field    the time field.
1070 * @return         the minimum value that this field could have, given the current date.
1071 * @draft ICU 2.6.
1072 */
getActualMinimum(UCalendarDateFields field,UErrorCode &) const1073 int32_t GregorianCalendar::getActualMinimum(UCalendarDateFields field, UErrorCode& /* status */) const
1074 {
1075     return getMinimum(field);
1076 }
1077 
1078 
1079 // ------------------------------------
1080 
1081 /**
1082 * Old year limits were least max 292269054, max 292278994.
1083 */
1084 
1085 /**
1086 * @stable ICU 2.0
1087 */
handleGetLimit(UCalendarDateFields field,ELimitType limitType) const1088 int32_t GregorianCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const {
1089     return kGregorianCalendarLimits[field][limitType];
1090 }
1091 
1092 /**
1093 * Return the maximum value that this field could have, given the current date.
1094 * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
1095 * maximum would be 28; for "Feb 3, 1996" it s 29.  Similarly for a Hebrew calendar,
1096 * for some years the actual maximum for MONTH is 12, and for others 13.
1097 * @stable ICU 2.0
1098 */
getActualMaximum(UCalendarDateFields field,UErrorCode & status) const1099 int32_t GregorianCalendar::getActualMaximum(UCalendarDateFields field, UErrorCode& status) const
1100 {
1101     /* It is a known limitation that the code here (and in getActualMinimum)
1102     * won't behave properly at the extreme limits of GregorianCalendar's
1103     * representable range (except for the code that handles the YEAR
1104     * field).  That's because the ends of the representable range are at
1105     * odd spots in the year.  For calendars with the default Gregorian
1106     * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun
1107     * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT
1108     * zones.  As a result, if the calendar is set to Aug 1 292278994 AD,
1109     * the actual maximum of DAY_OF_MONTH is 17, not 30.  If the date is Mar
1110     * 31 in that year, the actual maximum month might be Jul, whereas is
1111     * the date is Mar 15, the actual maximum might be Aug -- depending on
1112     * the precise semantics that are desired.  Similar considerations
1113     * affect all fields.  Nonetheless, this effect is sufficiently arcane
1114     * that we permit it, rather than complicating the code to handle such
1115     * intricacies. - liu 8/20/98
1116 
1117     * UPDATE: No longer true, since we have pulled in the limit values on
1118     * the year. - Liu 11/6/00 */
1119 
1120     switch (field) {
1121 
1122     case UCAL_YEAR:
1123         /* The year computation is no different, in principle, from the
1124         * others, however, the range of possible maxima is large.  In
1125         * addition, the way we know we've exceeded the range is different.
1126         * For these reasons, we use the special case code below to handle
1127         * this field.
1128         *
1129         * The actual maxima for YEAR depend on the type of calendar:
1130         *
1131         *     Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD
1132         *     Julian    = Dec  2, 292269055 BC - Jan  3, 292272993 AD
1133         *     Hybrid    = Dec  2, 292269055 BC - Aug 17, 292278994 AD
1134         *
1135         * We know we've exceeded the maximum when either the month, date,
1136         * time, or era changes in response to setting the year.  We don't
1137         * check for month, date, and time here because the year and era are
1138         * sufficient to detect an invalid year setting.  NOTE: If code is
1139         * added to check the month and date in the future for some reason,
1140         * Feb 29 must be allowed to shift to Mar 1 when setting the year.
1141         */
1142         {
1143             if(U_FAILURE(status)) return 0;
1144             Calendar *cal = clone();
1145             if(!cal) {
1146                 status = U_MEMORY_ALLOCATION_ERROR;
1147                 return 0;
1148             }
1149 
1150             cal->setLenient(true);
1151 
1152             int32_t era = cal->get(UCAL_ERA, status);
1153             UDate d = cal->getTime(status);
1154 
1155             /* Perform a binary search, with the invariant that lowGood is a
1156             * valid year, and highBad is an out of range year.
1157             */
1158             int32_t lowGood = kGregorianCalendarLimits[UCAL_YEAR][1];
1159             int32_t highBad = kGregorianCalendarLimits[UCAL_YEAR][2]+1;
1160             while ((lowGood + 1) < highBad) {
1161                 int32_t y = (lowGood + highBad) / 2;
1162                 cal->set(UCAL_YEAR, y);
1163                 if (cal->get(UCAL_YEAR, status) == y && cal->get(UCAL_ERA, status) == era) {
1164                     lowGood = y;
1165                 } else {
1166                     highBad = y;
1167                     cal->setTime(d, status); // Restore original fields
1168                 }
1169             }
1170 
1171             delete cal;
1172             return lowGood;
1173         }
1174 
1175     default:
1176         return Calendar::getActualMaximum(field,status);
1177     }
1178 }
1179 
1180 
handleGetExtendedYear(UErrorCode & status)1181 int32_t GregorianCalendar::handleGetExtendedYear(UErrorCode& status) {
1182     if (U_FAILURE(status)) {
1183         return 0;
1184     }
1185     // the year to return
1186     int32_t year = kEpochYear;
1187 
1188     // year field to use
1189     int32_t yearField = UCAL_EXTENDED_YEAR;
1190 
1191     // There are three separate fields which could be used to
1192     // derive the proper year.  Use the one most recently set.
1193     if (fStamp[yearField] < fStamp[UCAL_YEAR])
1194         yearField = UCAL_YEAR;
1195     if (fStamp[yearField] < fStamp[UCAL_YEAR_WOY])
1196         yearField = UCAL_YEAR_WOY;
1197 
1198     // based on the "best" year field, get the year
1199     switch(yearField) {
1200     case UCAL_EXTENDED_YEAR:
1201         year = internalGet(UCAL_EXTENDED_YEAR, kEpochYear);
1202         break;
1203 
1204     case UCAL_YEAR:
1205         {
1206             // The year defaults to the epoch start, the era to AD
1207             int32_t era = internalGet(UCAL_ERA, AD);
1208             if (era == BC) {
1209                 year = 1 - internalGet(UCAL_YEAR, 1); // Convert to extended year
1210             } else if (era == AD) {
1211                 year = internalGet(UCAL_YEAR, kEpochYear);
1212             } else {
1213                 status = U_ILLEGAL_ARGUMENT_ERROR;
1214                 return 0;
1215             }
1216         }
1217         break;
1218 
1219     case UCAL_YEAR_WOY:
1220         year = handleGetExtendedYearFromWeekFields(
1221             internalGet(UCAL_YEAR_WOY), internalGet(UCAL_WEEK_OF_YEAR), status);
1222         if (U_FAILURE(status)) {
1223             return 0;
1224         }
1225 #if defined (U_DEBUG_CAL)
1226         //    if(internalGet(UCAL_YEAR_WOY) != year) {
1227         fprintf(stderr, "%s:%d: hGEYFWF[%d,%d] ->  %d\n",
1228             __FILE__, __LINE__,internalGet(UCAL_YEAR_WOY),internalGet(UCAL_WEEK_OF_YEAR),year);
1229         //}
1230 #endif
1231         break;
1232 
1233     default:
1234         year = kEpochYear;
1235     }
1236     return year;
1237 }
1238 
handleGetExtendedYearFromWeekFields(int32_t yearWoy,int32_t woy,UErrorCode & status)1239 int32_t GregorianCalendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy, UErrorCode& status)
1240 {
1241     if (U_FAILURE(status)) {
1242         return 0;
1243     }
1244     // convert year to extended form
1245     int32_t era = internalGet(UCAL_ERA, AD);
1246     if(era == BC) {
1247         yearWoy = 1 - yearWoy;
1248     }
1249     return Calendar::handleGetExtendedYearFromWeekFields(yearWoy, woy, status);
1250 }
1251 
1252 
1253 // -------------------------------------
1254 
1255 /**
1256 * Return the ERA.  We need a special method for this because the
1257 * default ERA is AD, but a zero (unset) ERA is BC.
1258 */
1259 int32_t
internalGetEra() const1260 GregorianCalendar::internalGetEra() const {
1261     return isSet(UCAL_ERA) ? internalGet(UCAL_ERA) : static_cast<int32_t>(AD);
1262 }
1263 
1264 const char *
getType() const1265 GregorianCalendar::getType() const {
1266     //static const char kGregorianType = "gregorian";
1267 
1268     return "gregorian";
1269 }
1270 
1271 IMPL_SYSTEM_DEFAULT_CENTURY(GregorianCalendar, "@calendar=gregory")
1272 
1273 U_NAMESPACE_END
1274 
1275 #endif /* #if !UCONFIG_NO_FORMATTING */
1276 
1277 //eof
1278