xref: /aosp_15_r20/external/cronet/third_party/icu/source/i18n/gregocal.cpp (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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, (double)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 == 0) {
355         status = U_MEMORY_ALLOCATION_ERROR;
356         return;
357     }
358     if(U_FAILURE(status))
359         return;
360     cal->setTime(date, status);
361     fGregorianCutoverYear = cal->get(UCAL_YEAR, status);
362     if (cal->get(UCAL_ERA, status) == BC)
363         fGregorianCutoverYear = 1 - fGregorianCutoverYear;
364     fCutoverJulianDay = (int32_t)cutoverDay;
365     delete cal;
366 }
367 
368 
handleComputeFields(int32_t julianDay,UErrorCode & status)369 void GregorianCalendar::handleComputeFields(int32_t julianDay, UErrorCode& status) {
370     int32_t eyear, month, dayOfMonth, dayOfYear, unusedRemainder;
371 
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 
383     if (julianDay >= fCutoverJulianDay) {
384         month = getGregorianMonth();
385         dayOfMonth = getGregorianDayOfMonth();
386         dayOfYear = getGregorianDayOfYear();
387         eyear = getGregorianYear();
388     } else {
389         // The Julian epoch day (not the same as Julian Day)
390         // is zero on Saturday December 30, 0 (Gregorian).
391         int32_t julianEpochDay = julianDay - (kJan1_1JulianDay - 2);
392 		eyear = (int32_t) ClockMath::floorDivide((4.0*julianEpochDay) + 1464.0, (int32_t) 1461, &unusedRemainder);
393 
394         // Compute the Julian calendar day number for January 1, eyear
395         int32_t january1 = 365*(eyear-1) + ClockMath::floorDivide(eyear-1, (int32_t)4);
396         dayOfYear = (julianEpochDay - january1); // 0-based
397 
398         // Julian leap years occurred historically every 4 years starting
399         // with 8 AD.  Before 8 AD the spacing is irregular; every 3 years
400         // from 45 BC to 9 BC, and then none until 8 AD.  However, we don't
401         // implement this historical detail; instead, we implement the
402         // computationally cleaner proleptic calendar, which assumes
403         // consistent 4-year cycles throughout time.
404         UBool isLeap = ((eyear&0x3) == 0); // equiv. to (eyear%4 == 0)
405 
406         // Common Julian/Gregorian calculation
407         int32_t correction = 0;
408         int32_t march1 = isLeap ? 60 : 59; // zero-based DOY for March 1
409         if (dayOfYear >= march1) {
410             correction = isLeap ? 1 : 2;
411         }
412         month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month
413         dayOfMonth = dayOfYear - (isLeap?kLeapNumDays[month]:kNumDays[month]) + 1; // one-based DOM
414         ++dayOfYear;
415 #if defined (U_DEBUG_CAL)
416         //     fprintf(stderr, "%d - %d[%d] + 1\n", dayOfYear, isLeap?kLeapNumDays[month]:kNumDays[month], month );
417         //           fprintf(stderr, "%s:%d:  greg's HCF %d -> %d/%d/%d not %d/%d/%d\n",
418         //                   __FILE__, __LINE__,julianDay,
419         //          eyear,month,dayOfMonth,
420         //          getGregorianYear(), getGregorianMonth(), getGregorianDayOfMonth()  );
421         fprintf(stderr, "%s:%d: doy %d (greg's %d)- [cut=%d]\n",
422             __FILE__, __LINE__, dayOfYear, getGregorianDayOfYear(), fCutoverJulianDay);
423 #endif
424 
425     }
426 
427     // [j81] if we are after the cutover in its year, shift the day of the year
428     if((eyear == fGregorianCutoverYear) && (julianDay >= fCutoverJulianDay)) {
429         //from handleComputeMonthStart
430         int32_t gregShift = Grego::gregorianShift(eyear);
431 #if defined (U_DEBUG_CAL)
432         fprintf(stderr, "%s:%d:  gregorian shift %d :::  doy%d => %d [cut=%d]\n",
433             __FILE__, __LINE__,gregShift, dayOfYear, dayOfYear+gregShift, fCutoverJulianDay);
434 #endif
435         dayOfYear += gregShift;
436     }
437 
438     internalSet(UCAL_MONTH, month);
439     internalSet(UCAL_ORDINAL_MONTH, month);
440     internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);
441     internalSet(UCAL_DAY_OF_YEAR, dayOfYear);
442     internalSet(UCAL_EXTENDED_YEAR, eyear);
443     int32_t era = AD;
444     if (eyear < 1) {
445         era = BC;
446         eyear = 1 - eyear;
447     }
448     internalSet(UCAL_ERA, era);
449     internalSet(UCAL_YEAR, eyear);
450 }
451 
452 
453 // -------------------------------------
454 
455 UDate
getGregorianChange() const456 GregorianCalendar::getGregorianChange() const
457 {
458     return fGregorianCutover;
459 }
460 
461 // -------------------------------------
462 
463 UBool
isLeapYear(int32_t year) const464 GregorianCalendar::isLeapYear(int32_t year) const
465 {
466     // MSVC complains bitterly if we try to use Grego::isLeapYear here
467     // NOTE: year&0x3 == year%4
468     return (year >= fGregorianCutoverYear ?
469         (((year&0x3) == 0) && ((year%100 != 0) || (year%400 == 0))) : // Gregorian
470     ((year&0x3) == 0)); // Julian
471 }
472 
473 // -------------------------------------
474 
handleComputeJulianDay(UCalendarDateFields bestField)475 int32_t GregorianCalendar::handleComputeJulianDay(UCalendarDateFields bestField)
476 {
477     fInvertGregorian = false;
478 
479     int32_t jd = Calendar::handleComputeJulianDay(bestField);
480 
481     if((bestField == UCAL_WEEK_OF_YEAR) &&  // if we are doing WOY calculations, we are counting relative to Jan 1 *julian*
482         (internalGet(UCAL_EXTENDED_YEAR)==fGregorianCutoverYear) &&
483         jd >= fCutoverJulianDay) {
484             fInvertGregorian = true;  // So that the Julian Jan 1 will be used in handleComputeMonthStart
485             return Calendar::handleComputeJulianDay(bestField);
486         }
487 
488 
489         // The following check handles portions of the cutover year BEFORE the
490         // cutover itself happens.
491         //if ((fIsGregorian==true) != (jd >= fCutoverJulianDay)) {  /*  cutoverJulianDay)) { */
492         if ((fIsGregorian) != (jd >= fCutoverJulianDay)) {  /*  cutoverJulianDay)) { */
493 #if defined (U_DEBUG_CAL)
494             fprintf(stderr, "%s:%d: jd [invert] %d\n",
495                 __FILE__, __LINE__, jd);
496 #endif
497             fInvertGregorian = true;
498             jd = Calendar::handleComputeJulianDay(bestField);
499 #if defined (U_DEBUG_CAL)
500             fprintf(stderr, "%s:%d:  fIsGregorian %s, fInvertGregorian %s - ",
501                 __FILE__, __LINE__,fIsGregorian?"T":"F", fInvertGregorian?"T":"F");
502             fprintf(stderr, " jd NOW %d\n",
503                 jd);
504 #endif
505         } else {
506 #if defined (U_DEBUG_CAL)
507             fprintf(stderr, "%s:%d: jd [==] %d - %sfIsGregorian %sfInvertGregorian, %d\n",
508                 __FILE__, __LINE__, jd, fIsGregorian?"T":"F", fInvertGregorian?"T":"F", bestField);
509 #endif
510         }
511 
512         if(fIsGregorian && (internalGet(UCAL_EXTENDED_YEAR) == fGregorianCutoverYear)) {
513             int32_t gregShift = Grego::gregorianShift(internalGet(UCAL_EXTENDED_YEAR));
514             if (bestField == UCAL_DAY_OF_YEAR) {
515 #if defined (U_DEBUG_CAL)
516                 fprintf(stderr, "%s:%d: [DOY%d] gregorian shift of JD %d += %d\n",
517                     __FILE__, __LINE__, fFields[bestField],jd, gregShift);
518 #endif
519                 jd -= gregShift;
520             } else if ( bestField == UCAL_WEEK_OF_MONTH ) {
521                 int32_t weekShift = 14;
522 #if defined (U_DEBUG_CAL)
523                 fprintf(stderr, "%s:%d: [WOY/WOM] gregorian week shift of %d += %d\n",
524                     __FILE__, __LINE__, jd, weekShift);
525 #endif
526                 jd += weekShift; // shift by weeks for week based fields.
527             }
528         }
529 
530         return jd;
531 }
532 
handleComputeMonthStart(int32_t eyear,int32_t month,UBool) const533 int32_t GregorianCalendar::handleComputeMonthStart(int32_t eyear, int32_t month,
534 
535                                                    UBool /* useMonth */) const
536 {
537     GregorianCalendar *nonConstThis = (GregorianCalendar*)this; // cast away const
538 
539     // If the month is out of range, adjust it into range, and
540     // modify the extended year value accordingly.
541     if (month < 0 || month > 11) {
542         eyear += ClockMath::floorDivide(month, 12, &month);
543     }
544 
545     UBool isLeap = eyear%4 == 0;
546     int64_t y = (int64_t)eyear-1;
547     int64_t julianDay = 365*y + ClockMath::floorDivide(y, (int64_t)4) + (kJan1_1JulianDay - 3);
548 
549     nonConstThis->fIsGregorian = (eyear >= fGregorianCutoverYear);
550 #if defined (U_DEBUG_CAL)
551     fprintf(stderr, "%s:%d: (hcms%d/%d) fIsGregorian %s, fInvertGregorian %s\n",
552         __FILE__, __LINE__, eyear,month, fIsGregorian?"T":"F", fInvertGregorian?"T":"F");
553 #endif
554     if (fInvertGregorian) {
555         nonConstThis->fIsGregorian = !fIsGregorian;
556     }
557     if (fIsGregorian) {
558         isLeap = isLeap && ((eyear%100 != 0) || (eyear%400 == 0));
559         // Add 2 because Gregorian calendar starts 2 days after
560         // Julian calendar
561         int32_t gregShift = Grego::gregorianShift(eyear);
562 #if defined (U_DEBUG_CAL)
563         fprintf(stderr, "%s:%d: (hcms%d/%d) gregorian shift of %d += %d\n",
564             __FILE__, __LINE__, eyear, month, julianDay, gregShift);
565 #endif
566         julianDay += gregShift;
567     }
568 
569     // At this point julianDay indicates the day BEFORE the first
570     // day of January 1, <eyear> of either the Julian or Gregorian
571     // calendar.
572 
573     if (month != 0) {
574         julianDay += isLeap?kLeapNumDays[month]:kNumDays[month];
575     }
576 
577     return static_cast<int32_t>(julianDay);
578 }
579 
handleGetMonthLength(int32_t extendedYear,int32_t month) const580 int32_t GregorianCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month)  const
581 {
582     // If the month is out of range, adjust it into range, and
583     // modify the extended year value accordingly.
584     if (month < 0 || month > 11) {
585         extendedYear += ClockMath::floorDivide(month, 12, &month);
586     }
587 
588     return isLeapYear(extendedYear) ? kLeapMonthLength[month] : kMonthLength[month];
589 }
590 
handleGetYearLength(int32_t eyear) const591 int32_t GregorianCalendar::handleGetYearLength(int32_t eyear) const {
592     return isLeapYear(eyear) ? 366 : 365;
593 }
594 
595 
596 int32_t
monthLength(int32_t month) const597 GregorianCalendar::monthLength(int32_t month) const
598 {
599     int32_t year = internalGet(UCAL_EXTENDED_YEAR);
600     return handleGetMonthLength(year, month);
601 }
602 
603 // -------------------------------------
604 
605 int32_t
monthLength(int32_t month,int32_t year) const606 GregorianCalendar::monthLength(int32_t month, int32_t year) const
607 {
608     return isLeapYear(year) ? kLeapMonthLength[month] : kMonthLength[month];
609 }
610 
611 // -------------------------------------
612 
613 int32_t
yearLength() const614 GregorianCalendar::yearLength() const
615 {
616     return isLeapYear(internalGet(UCAL_YEAR)) ? 366 : 365;
617 }
618 
619 // -------------------------------------
620 
621 UBool
validateFields() const622 GregorianCalendar::validateFields() const
623 {
624     for (int32_t field = 0; field < UCAL_FIELD_COUNT; field++) {
625         // Ignore DATE and DAY_OF_YEAR which are handled below
626         if (field != UCAL_DATE &&
627             field != UCAL_DAY_OF_YEAR &&
628             isSet((UCalendarDateFields)field) &&
629             ! boundsCheck(internalGet((UCalendarDateFields)field), (UCalendarDateFields)field))
630             return false;
631     }
632 
633     // Values differ in Least-Maximum and Maximum should be handled
634     // specially.
635     if (isSet(UCAL_DATE)) {
636         int32_t date = internalGet(UCAL_DATE);
637         if (date < getMinimum(UCAL_DATE) ||
638             date > monthLength(internalGetMonth())) {
639                 return false;
640             }
641     }
642 
643     if (isSet(UCAL_DAY_OF_YEAR)) {
644         int32_t days = internalGet(UCAL_DAY_OF_YEAR);
645         if (days < 1 || days > yearLength()) {
646             return false;
647         }
648     }
649 
650     // Handle DAY_OF_WEEK_IN_MONTH, which must not have the value zero.
651     // We've checked against minimum and maximum above already.
652     if (isSet(UCAL_DAY_OF_WEEK_IN_MONTH) &&
653         0 == internalGet(UCAL_DAY_OF_WEEK_IN_MONTH)) {
654             return false;
655         }
656 
657         return true;
658 }
659 
660 // -------------------------------------
661 
662 UBool
boundsCheck(int32_t value,UCalendarDateFields field) const663 GregorianCalendar::boundsCheck(int32_t value, UCalendarDateFields field) const
664 {
665     return value >= getMinimum(field) && value <= getMaximum(field);
666 }
667 
668 // -------------------------------------
669 
670 UDate
getEpochDay(UErrorCode & status)671 GregorianCalendar::getEpochDay(UErrorCode& status)
672 {
673     complete(status);
674     // Divide by 1000 (convert to seconds) in order to prevent overflow when
675     // dealing with UDate(Long.MIN_VALUE) and UDate(Long.MAX_VALUE).
676     double wallSec = internalGetTime()/1000 + (internalGet(UCAL_ZONE_OFFSET) + internalGet(UCAL_DST_OFFSET))/1000;
677 
678     return ClockMath::floorDivide(wallSec, kOneDay/1000.0);
679 }
680 
681 // -------------------------------------
682 
683 
684 // -------------------------------------
685 
686 /**
687 * Compute the julian day number of the day BEFORE the first day of
688 * January 1, year 1 of the given calendar.  If julianDay == 0, it
689 * specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
690 * or Gregorian).
691 */
computeJulianDayOfYear(UBool isGregorian,int32_t year,UBool & isLeap)692 double GregorianCalendar::computeJulianDayOfYear(UBool isGregorian,
693                                                  int32_t year, UBool& isLeap)
694 {
695     isLeap = year%4 == 0;
696     int32_t y = year - 1;
697     double julianDay = 365.0*y + ClockMath::floorDivide(y, 4) + (kJan1_1JulianDay - 3);
698 
699     if (isGregorian) {
700         isLeap = isLeap && ((year%100 != 0) || (year%400 == 0));
701         // Add 2 because Gregorian calendar starts 2 days after Julian calendar
702         julianDay += Grego::gregorianShift(year);
703     }
704 
705     return julianDay;
706 }
707 
708 // /**
709 //  * Compute the day of week, relative to the first day of week, from
710 //  * 0..6, of the current DOW_LOCAL or DAY_OF_WEEK fields.  This is
711 //  * equivalent to get(DOW_LOCAL) - 1.
712 //  */
713 // int32_t GregorianCalendar::computeRelativeDOW() const {
714 //     int32_t relDow = 0;
715 //     if (fStamp[UCAL_DOW_LOCAL] > fStamp[UCAL_DAY_OF_WEEK]) {
716 //         relDow = internalGet(UCAL_DOW_LOCAL) - 1; // 1-based
717 //     } else if (fStamp[UCAL_DAY_OF_WEEK] != kUnset) {
718 //         relDow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
719 //         if (relDow < 0) relDow += 7;
720 //     }
721 //     return relDow;
722 // }
723 
724 // /**
725 //  * Compute the day of week, relative to the first day of week,
726 //  * from 0..6 of the given julian day.
727 //  */
728 // int32_t GregorianCalendar::computeRelativeDOW(double julianDay) const {
729 //   int32_t relDow = julianDayToDayOfWeek(julianDay) - getFirstDayOfWeek();
730 //     if (relDow < 0) {
731 //         relDow += 7;
732 //     }
733 //     return relDow;
734 // }
735 
736 // /**
737 //  * Compute the DOY using the WEEK_OF_YEAR field and the julian day
738 //  * of the day BEFORE January 1 of a year (a return value from
739 //  * computeJulianDayOfYear).
740 //  */
741 // int32_t GregorianCalendar::computeDOYfromWOY(double julianDayOfYear) const {
742 //     // Compute DOY from day of week plus week of year
743 
744 //     // Find the day of the week for the first of this year.  This
745 //     // is zero-based, with 0 being the locale-specific first day of
746 //     // the week.  Add 1 to get first day of year.
747 //     int32_t fdy = computeRelativeDOW(julianDayOfYear + 1);
748 
749 //     return
750 //         // Compute doy of first (relative) DOW of WOY 1
751 //         (((7 - fdy) < getMinimalDaysInFirstWeek())
752 //          ? (8 - fdy) : (1 - fdy))
753 
754 //         // Adjust for the week number.
755 //         + (7 * (internalGet(UCAL_WEEK_OF_YEAR) - 1))
756 
757 //         // Adjust for the DOW
758 //         + computeRelativeDOW();
759 // }
760 
761 // -------------------------------------
762 
763 double
millisToJulianDay(UDate millis)764 GregorianCalendar::millisToJulianDay(UDate millis)
765 {
766     return (double)kEpochStartAsJulianDay + ClockMath::floorDivide(millis, (double)kOneDay);
767 }
768 
769 // -------------------------------------
770 
771 UDate
julianDayToMillis(double julian)772 GregorianCalendar::julianDayToMillis(double julian)
773 {
774     return (UDate) ((julian - kEpochStartAsJulianDay) * (double) kOneDay);
775 }
776 
777 // -------------------------------------
778 
779 int32_t
aggregateStamp(int32_t stamp_a,int32_t stamp_b)780 GregorianCalendar::aggregateStamp(int32_t stamp_a, int32_t stamp_b)
781 {
782     return (((stamp_a != kUnset && stamp_b != kUnset)
783         ? uprv_max(stamp_a, stamp_b)
784         : (int32_t)kUnset));
785 }
786 
787 // -------------------------------------
788 
789 /**
790 * Roll a field by a signed amount.
791 * Note: This will be made public later. [LIU]
792 */
793 
794 void
roll(EDateFields field,int32_t amount,UErrorCode & status)795 GregorianCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) {
796     roll((UCalendarDateFields) field, amount, status);
797 }
798 
799 void
roll(UCalendarDateFields field,int32_t amount,UErrorCode & status)800 GregorianCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) UPRV_NO_SANITIZE_UNDEFINED {
801     if((amount == 0) || U_FAILURE(status)) {
802         return;
803     }
804 
805     // J81 processing. (gregorian cutover)
806     UBool inCutoverMonth = false;
807     int32_t cMonthLen=0; // 'c' for cutover; in days
808     int32_t cDayOfMonth=0; // no discontinuity: [0, cMonthLen)
809     double cMonthStart=0.0; // in ms
810 
811     // Common code - see if we're in the cutover month of the cutover year
812     if(get(UCAL_EXTENDED_YEAR, status) == fGregorianCutoverYear) {
813         switch (field) {
814         case UCAL_DAY_OF_MONTH:
815         case UCAL_WEEK_OF_MONTH:
816             {
817                 int32_t max = monthLength(internalGetMonth());
818                 UDate t = internalGetTime();
819                 // We subtract 1 from the DAY_OF_MONTH to make it zero-based, and an
820                 // additional 10 if we are after the cutover. Thus the monthStart
821                 // value will be correct iff we actually are in the cutover month.
822                 cDayOfMonth = internalGet(UCAL_DAY_OF_MONTH) - ((t >= fGregorianCutover) ? 10 : 0);
823                 cMonthStart = t - ((cDayOfMonth - 1) * kOneDay);
824                 // A month containing the cutover is 10 days shorter.
825                 if ((cMonthStart < fGregorianCutover) &&
826                     (cMonthStart + (cMonthLen=(max-10))*kOneDay >= fGregorianCutover)) {
827                         inCutoverMonth = true;
828                     }
829             }
830             break;
831         default:
832             ;
833         }
834     }
835 
836     switch (field) {
837     case UCAL_WEEK_OF_YEAR: {
838         // Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the
839         // week.  Also, rolling the week of the year can have seemingly
840         // strange effects simply because the year of the week of year
841         // may be different from the calendar year.  For example, the
842         // date Dec 28, 1997 is the first day of week 1 of 1998 (if
843         // weeks start on Sunday and the minimal days in first week is
844         // <= 3).
845         int32_t woy = get(UCAL_WEEK_OF_YEAR, status);
846         // Get the ISO year, which matches the week of year.  This
847         // may be one year before or after the calendar year.
848         int32_t isoYear = get(UCAL_YEAR_WOY, status);
849         int32_t isoDoy = internalGet(UCAL_DAY_OF_YEAR);
850         if (internalGetMonth() == UCAL_JANUARY) {
851             if (woy >= 52) {
852                 isoDoy += handleGetYearLength(isoYear);
853             }
854         } else {
855             if (woy == 1) {
856                 isoDoy -= handleGetYearLength(isoYear - 1);
857             }
858         }
859         woy += amount;
860         // Do fast checks to avoid unnecessary computation:
861         if (woy < 1 || woy > 52) {
862             // Determine the last week of the ISO year.
863             // We do this using the standard formula we use
864             // everywhere in this file.  If we can see that the
865             // days at the end of the year are going to fall into
866             // week 1 of the next year, we drop the last week by
867             // subtracting 7 from the last day of the year.
868             int32_t lastDoy = handleGetYearLength(isoYear);
869             int32_t lastRelDow = (lastDoy - isoDoy + internalGet(UCAL_DAY_OF_WEEK) -
870                 getFirstDayOfWeek()) % 7;
871             if (lastRelDow < 0) lastRelDow += 7;
872             if ((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) lastDoy -= 7;
873             int32_t lastWoy = weekNumber(lastDoy, lastRelDow + 1);
874             woy = ((woy + lastWoy - 1) % lastWoy) + 1;
875         }
876         set(UCAL_WEEK_OF_YEAR, woy);
877         set(UCAL_YEAR_WOY,isoYear);
878         return;
879                             }
880 
881     case UCAL_DAY_OF_MONTH:
882         if( !inCutoverMonth ) {
883             Calendar::roll(field, amount, status);
884             return;
885         } else {
886             // [j81] 1582 special case for DOM
887             // The default computation works except when the current month
888             // contains the Gregorian cutover.  We handle this special case
889             // here.  [j81 - aliu]
890             double monthLen = cMonthLen * kOneDay;
891             double msIntoMonth = uprv_fmod(internalGetTime() - cMonthStart +
892                 amount * kOneDay, monthLen);
893             if (msIntoMonth < 0) {
894                 msIntoMonth += monthLen;
895             }
896 #if defined (U_DEBUG_CAL)
897             fprintf(stderr, "%s:%d: roll DOM %d  -> %.0lf ms  \n",
898                 __FILE__, __LINE__,amount, cMonthLen, cMonthStart+msIntoMonth);
899 #endif
900             setTimeInMillis(cMonthStart + msIntoMonth, status);
901             return;
902         }
903 
904     case UCAL_WEEK_OF_MONTH:
905         if( !inCutoverMonth ) {
906             Calendar::roll(field, amount, status);
907             return;
908         } else {
909 #if defined (U_DEBUG_CAL)
910             fprintf(stderr, "%s:%d: roll WOM %d ??????????????????? \n",
911                 __FILE__, __LINE__,amount);
912 #endif
913             // NOTE: following copied from  the old
914             //     GregorianCalendar::roll( WEEK_OF_MONTH )  code
915 
916             // This is tricky, because during the roll we may have to shift
917             // to a different day of the week.  For example:
918 
919             //    s  m  t  w  r  f  s
920             //          1  2  3  4  5
921             //    6  7  8  9 10 11 12
922 
923             // When rolling from the 6th or 7th back one week, we go to the
924             // 1st (assuming that the first partial week counts).  The same
925             // thing happens at the end of the month.
926 
927             // The other tricky thing is that we have to figure out whether
928             // the first partial week actually counts or not, based on the
929             // minimal first days in the week.  And we have to use the
930             // correct first day of the week to delineate the week
931             // boundaries.
932 
933             // Here's our algorithm.  First, we find the real boundaries of
934             // the month.  Then we discard the first partial week if it
935             // doesn't count in this locale.  Then we fill in the ends with
936             // phantom days, so that the first partial week and the last
937             // partial week are full weeks.  We then have a nice square
938             // block of weeks.  We do the usual rolling within this block,
939             // as is done elsewhere in this method.  If we wind up on one of
940             // the phantom days that we added, we recognize this and pin to
941             // the first or the last day of the month.  Easy, eh?
942 
943             // Another wrinkle: To fix jitterbug 81, we have to make all this
944             // work in the oddball month containing the Gregorian cutover.
945             // This month is 10 days shorter than usual, and also contains
946             // a discontinuity in the days; e.g., the default cutover month
947             // is Oct 1582, and goes from day of month 4 to day of month 15.
948 
949             // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
950             // in this locale.  We have dow in 0..6.
951             int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
952             if (dow < 0)
953                 dow += 7;
954 
955             // Find the day of month, compensating for cutover discontinuity.
956             int32_t dom = cDayOfMonth;
957 
958             // Find the day of the week (normalized for locale) for the first
959             // of the month.
960             int32_t fdm = (dow - dom + 1) % 7;
961             if (fdm < 0)
962                 fdm += 7;
963 
964             // Get the first day of the first full week of the month,
965             // including phantom days, if any.  Figure out if the first week
966             // counts or not; if it counts, then fill in phantom days.  If
967             // not, advance to the first real full week (skip the partial week).
968             int32_t start;
969             if ((7 - fdm) < getMinimalDaysInFirstWeek())
970                 start = 8 - fdm; // Skip the first partial week
971             else
972                 start = 1 - fdm; // This may be zero or negative
973 
974             // Get the day of the week (normalized for locale) for the last
975             // day of the month.
976             int32_t monthLen = cMonthLen;
977             int32_t ldm = (monthLen - dom + dow) % 7;
978             // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here.
979 
980             // Get the limit day for the blocked-off rectangular month; that
981             // is, the day which is one past the last day of the month,
982             // after the month has already been filled in with phantom days
983             // to fill out the last week.  This day has a normalized DOW of 0.
984             int32_t limit = monthLen + 7 - ldm;
985 
986             // Now roll between start and (limit - 1).
987             int32_t gap = limit - start;
988             int32_t newDom = (dom + amount*7 - start) % gap;
989             if (newDom < 0)
990                 newDom += gap;
991             newDom += start;
992 
993             // Finally, pin to the real start and end of the month.
994             if (newDom < 1)
995                 newDom = 1;
996             if (newDom > monthLen)
997                 newDom = monthLen;
998 
999             // Set the DAY_OF_MONTH.  We rely on the fact that this field
1000             // takes precedence over everything else (since all other fields
1001             // are also set at this point).  If this fact changes (if the
1002             // disambiguation algorithm changes) then we will have to unset
1003             // the appropriate fields here so that DAY_OF_MONTH is attended
1004             // to.
1005 
1006             // If we are in the cutover month, manipulate ms directly.  Don't do
1007             // this in general because it doesn't work across DST boundaries
1008             // (details, details).  This takes care of the discontinuity.
1009             setTimeInMillis(cMonthStart + (newDom-1)*kOneDay, status);
1010             return;
1011         }
1012 
1013     default:
1014         Calendar::roll(field, amount, status);
1015         return;
1016     }
1017 }
1018 
1019 // -------------------------------------
1020 
1021 
1022 /**
1023 * Return the minimum value that this field could have, given the current date.
1024 * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
1025 * @param field    the time field.
1026 * @return         the minimum value that this field could have, given the current date.
1027 * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead.
1028 */
getActualMinimum(EDateFields field) const1029 int32_t GregorianCalendar::getActualMinimum(EDateFields field) const
1030 {
1031     return getMinimum((UCalendarDateFields)field);
1032 }
1033 
getActualMinimum(EDateFields field,UErrorCode &) const1034 int32_t GregorianCalendar::getActualMinimum(EDateFields field, UErrorCode& /* status */) const
1035 {
1036     return getMinimum((UCalendarDateFields)field);
1037 }
1038 
1039 /**
1040 * Return the minimum value that this field could have, given the current date.
1041 * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
1042 * @param field    the time field.
1043 * @return         the minimum value that this field could have, given the current date.
1044 * @draft ICU 2.6.
1045 */
getActualMinimum(UCalendarDateFields field,UErrorCode &) const1046 int32_t GregorianCalendar::getActualMinimum(UCalendarDateFields field, UErrorCode& /* status */) const
1047 {
1048     return getMinimum(field);
1049 }
1050 
1051 
1052 // ------------------------------------
1053 
1054 /**
1055 * Old year limits were least max 292269054, max 292278994.
1056 */
1057 
1058 /**
1059 * @stable ICU 2.0
1060 */
handleGetLimit(UCalendarDateFields field,ELimitType limitType) const1061 int32_t GregorianCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const {
1062     return kGregorianCalendarLimits[field][limitType];
1063 }
1064 
1065 /**
1066 * Return the maximum value that this field could have, given the current date.
1067 * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
1068 * maximum would be 28; for "Feb 3, 1996" it s 29.  Similarly for a Hebrew calendar,
1069 * for some years the actual maximum for MONTH is 12, and for others 13.
1070 * @stable ICU 2.0
1071 */
getActualMaximum(UCalendarDateFields field,UErrorCode & status) const1072 int32_t GregorianCalendar::getActualMaximum(UCalendarDateFields field, UErrorCode& status) const
1073 {
1074     /* It is a known limitation that the code here (and in getActualMinimum)
1075     * won't behave properly at the extreme limits of GregorianCalendar's
1076     * representable range (except for the code that handles the YEAR
1077     * field).  That's because the ends of the representable range are at
1078     * odd spots in the year.  For calendars with the default Gregorian
1079     * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun
1080     * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT
1081     * zones.  As a result, if the calendar is set to Aug 1 292278994 AD,
1082     * the actual maximum of DAY_OF_MONTH is 17, not 30.  If the date is Mar
1083     * 31 in that year, the actual maximum month might be Jul, whereas is
1084     * the date is Mar 15, the actual maximum might be Aug -- depending on
1085     * the precise semantics that are desired.  Similar considerations
1086     * affect all fields.  Nonetheless, this effect is sufficiently arcane
1087     * that we permit it, rather than complicating the code to handle such
1088     * intricacies. - liu 8/20/98
1089 
1090     * UPDATE: No longer true, since we have pulled in the limit values on
1091     * the year. - Liu 11/6/00 */
1092 
1093     switch (field) {
1094 
1095     case UCAL_YEAR:
1096         /* The year computation is no different, in principle, from the
1097         * others, however, the range of possible maxima is large.  In
1098         * addition, the way we know we've exceeded the range is different.
1099         * For these reasons, we use the special case code below to handle
1100         * this field.
1101         *
1102         * The actual maxima for YEAR depend on the type of calendar:
1103         *
1104         *     Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD
1105         *     Julian    = Dec  2, 292269055 BC - Jan  3, 292272993 AD
1106         *     Hybrid    = Dec  2, 292269055 BC - Aug 17, 292278994 AD
1107         *
1108         * We know we've exceeded the maximum when either the month, date,
1109         * time, or era changes in response to setting the year.  We don't
1110         * check for month, date, and time here because the year and era are
1111         * sufficient to detect an invalid year setting.  NOTE: If code is
1112         * added to check the month and date in the future for some reason,
1113         * Feb 29 must be allowed to shift to Mar 1 when setting the year.
1114         */
1115         {
1116             if(U_FAILURE(status)) return 0;
1117             Calendar *cal = clone();
1118             if(!cal) {
1119                 status = U_MEMORY_ALLOCATION_ERROR;
1120                 return 0;
1121             }
1122 
1123             cal->setLenient(true);
1124 
1125             int32_t era = cal->get(UCAL_ERA, status);
1126             UDate d = cal->getTime(status);
1127 
1128             /* Perform a binary search, with the invariant that lowGood is a
1129             * valid year, and highBad is an out of range year.
1130             */
1131             int32_t lowGood = kGregorianCalendarLimits[UCAL_YEAR][1];
1132             int32_t highBad = kGregorianCalendarLimits[UCAL_YEAR][2]+1;
1133             while ((lowGood + 1) < highBad) {
1134                 int32_t y = (lowGood + highBad) / 2;
1135                 cal->set(UCAL_YEAR, y);
1136                 if (cal->get(UCAL_YEAR, status) == y && cal->get(UCAL_ERA, status) == era) {
1137                     lowGood = y;
1138                 } else {
1139                     highBad = y;
1140                     cal->setTime(d, status); // Restore original fields
1141                 }
1142             }
1143 
1144             delete cal;
1145             return lowGood;
1146         }
1147 
1148     default:
1149         return Calendar::getActualMaximum(field,status);
1150     }
1151 }
1152 
1153 
handleGetExtendedYear()1154 int32_t GregorianCalendar::handleGetExtendedYear() {
1155     // the year to return
1156     int32_t year = kEpochYear;
1157 
1158     // year field to use
1159     int32_t yearField = UCAL_EXTENDED_YEAR;
1160 
1161     // There are three separate fields which could be used to
1162     // derive the proper year.  Use the one most recently set.
1163     if (fStamp[yearField] < fStamp[UCAL_YEAR])
1164         yearField = UCAL_YEAR;
1165     if (fStamp[yearField] < fStamp[UCAL_YEAR_WOY])
1166         yearField = UCAL_YEAR_WOY;
1167 
1168     // based on the "best" year field, get the year
1169     switch(yearField) {
1170     case UCAL_EXTENDED_YEAR:
1171         year = internalGet(UCAL_EXTENDED_YEAR, kEpochYear);
1172         break;
1173 
1174     case UCAL_YEAR:
1175         {
1176             // The year defaults to the epoch start, the era to AD
1177             int32_t era = internalGet(UCAL_ERA, AD);
1178             if (era == BC) {
1179                 year = 1 - internalGet(UCAL_YEAR, 1); // Convert to extended year
1180             } else {
1181                 year = internalGet(UCAL_YEAR, kEpochYear);
1182             }
1183         }
1184         break;
1185 
1186     case UCAL_YEAR_WOY:
1187         year = handleGetExtendedYearFromWeekFields(internalGet(UCAL_YEAR_WOY), internalGet(UCAL_WEEK_OF_YEAR));
1188 #if defined (U_DEBUG_CAL)
1189         //    if(internalGet(UCAL_YEAR_WOY) != year) {
1190         fprintf(stderr, "%s:%d: hGEYFWF[%d,%d] ->  %d\n",
1191             __FILE__, __LINE__,internalGet(UCAL_YEAR_WOY),internalGet(UCAL_WEEK_OF_YEAR),year);
1192         //}
1193 #endif
1194         break;
1195 
1196     default:
1197         year = kEpochYear;
1198     }
1199     return year;
1200 }
1201 
handleGetExtendedYearFromWeekFields(int32_t yearWoy,int32_t woy)1202 int32_t GregorianCalendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy)
1203 {
1204     // convert year to extended form
1205     int32_t era = internalGet(UCAL_ERA, AD);
1206     if(era == BC) {
1207         yearWoy = 1 - yearWoy;
1208     }
1209     return Calendar::handleGetExtendedYearFromWeekFields(yearWoy, woy);
1210 }
1211 
1212 
1213 // -------------------------------------
1214 
1215 /**
1216 * Return the ERA.  We need a special method for this because the
1217 * default ERA is AD, but a zero (unset) ERA is BC.
1218 */
1219 int32_t
internalGetEra() const1220 GregorianCalendar::internalGetEra() const {
1221     return isSet(UCAL_ERA) ? internalGet(UCAL_ERA) : (int32_t)AD;
1222 }
1223 
1224 const char *
getType() const1225 GregorianCalendar::getType() const {
1226     //static const char kGregorianType = "gregorian";
1227 
1228     return "gregorian";
1229 }
1230 
1231 /**
1232  * The system maintains a static default century start date and Year.  They are
1233  * initialized the first time they are used.  Once the system default century date
1234  * and year are set, they do not change.
1235  */
1236 static UDate           gSystemDefaultCenturyStart       = DBL_MIN;
1237 static int32_t         gSystemDefaultCenturyStartYear   = -1;
1238 static icu::UInitOnce  gSystemDefaultCenturyInit        {};
1239 
1240 
haveDefaultCentury() const1241 UBool GregorianCalendar::haveDefaultCentury() const
1242 {
1243     return true;
1244 }
1245 
1246 static void U_CALLCONV
initializeSystemDefaultCentury()1247 initializeSystemDefaultCentury()
1248 {
1249     // initialize systemDefaultCentury and systemDefaultCenturyYear based
1250     // on the current time.  They'll be set to 80 years before
1251     // the current time.
1252     UErrorCode status = U_ZERO_ERROR;
1253     GregorianCalendar calendar(status);
1254     if (U_SUCCESS(status)) {
1255         calendar.setTime(Calendar::getNow(), status);
1256         calendar.add(UCAL_YEAR, -80, status);
1257 
1258         gSystemDefaultCenturyStart = calendar.getTime(status);
1259         gSystemDefaultCenturyStartYear = calendar.get(UCAL_YEAR, status);
1260     }
1261     // We have no recourse upon failure unless we want to propagate the failure
1262     // out.
1263 }
1264 
defaultCenturyStart() const1265 UDate GregorianCalendar::defaultCenturyStart() const {
1266     // lazy-evaluate systemDefaultCenturyStart
1267     umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury);
1268     return gSystemDefaultCenturyStart;
1269 }
1270 
defaultCenturyStartYear() const1271 int32_t GregorianCalendar::defaultCenturyStartYear() const {
1272     // lazy-evaluate systemDefaultCenturyStartYear
1273     umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury);
1274     return gSystemDefaultCenturyStartYear;
1275 }
1276 
1277 U_NAMESPACE_END
1278 
1279 #endif /* #if !UCONFIG_NO_FORMATTING */
1280 
1281 //eof
1282