• 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, (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(int32_t year) const614 GregorianCalendar::yearLength(int32_t year) const
615 {
616     return isLeapYear(year) ? 366 : 365;
617 }
618 
619 // -------------------------------------
620 
621 int32_t
yearLength() const622 GregorianCalendar::yearLength() const
623 {
624     return isLeapYear(internalGet(UCAL_YEAR)) ? 366 : 365;
625 }
626 
627 // -------------------------------------
628 
629 /**
630 * After adjustments such as add(MONTH), add(YEAR), we don't want the
631 * month to jump around.  E.g., we don't want Jan 31 + 1 month to go to Mar
632 * 3, we want it to go to Feb 28.  Adjustments which might run into this
633 * problem call this method to retain the proper month.
634 */
635 void
pinDayOfMonth()636 GregorianCalendar::pinDayOfMonth()
637 {
638     int32_t monthLen = monthLength(internalGetMonth());
639     int32_t dom = internalGet(UCAL_DATE);
640     if(dom > monthLen)
641         set(UCAL_DATE, monthLen);
642 }
643 
644 // -------------------------------------
645 
646 
647 UBool
validateFields() const648 GregorianCalendar::validateFields() const
649 {
650     for (int32_t field = 0; field < UCAL_FIELD_COUNT; field++) {
651         // Ignore DATE and DAY_OF_YEAR which are handled below
652         if (field != UCAL_DATE &&
653             field != UCAL_DAY_OF_YEAR &&
654             isSet((UCalendarDateFields)field) &&
655             ! boundsCheck(internalGet((UCalendarDateFields)field), (UCalendarDateFields)field))
656             return false;
657     }
658 
659     // Values differ in Least-Maximum and Maximum should be handled
660     // specially.
661     if (isSet(UCAL_DATE)) {
662         int32_t date = internalGet(UCAL_DATE);
663         if (date < getMinimum(UCAL_DATE) ||
664             date > monthLength(internalGetMonth())) {
665                 return false;
666             }
667     }
668 
669     if (isSet(UCAL_DAY_OF_YEAR)) {
670         int32_t days = internalGet(UCAL_DAY_OF_YEAR);
671         if (days < 1 || days > yearLength()) {
672             return false;
673         }
674     }
675 
676     // Handle DAY_OF_WEEK_IN_MONTH, which must not have the value zero.
677     // We've checked against minimum and maximum above already.
678     if (isSet(UCAL_DAY_OF_WEEK_IN_MONTH) &&
679         0 == internalGet(UCAL_DAY_OF_WEEK_IN_MONTH)) {
680             return false;
681         }
682 
683         return true;
684 }
685 
686 // -------------------------------------
687 
688 UBool
boundsCheck(int32_t value,UCalendarDateFields field) const689 GregorianCalendar::boundsCheck(int32_t value, UCalendarDateFields field) const
690 {
691     return value >= getMinimum(field) && value <= getMaximum(field);
692 }
693 
694 // -------------------------------------
695 
696 UDate
getEpochDay(UErrorCode & status)697 GregorianCalendar::getEpochDay(UErrorCode& status)
698 {
699     complete(status);
700     // Divide by 1000 (convert to seconds) in order to prevent overflow when
701     // dealing with UDate(Long.MIN_VALUE) and UDate(Long.MAX_VALUE).
702     double wallSec = internalGetTime()/1000 + (internalGet(UCAL_ZONE_OFFSET) + internalGet(UCAL_DST_OFFSET))/1000;
703 
704     return ClockMath::floorDivide(wallSec, kOneDay/1000.0);
705 }
706 
707 // -------------------------------------
708 
709 
710 // -------------------------------------
711 
712 /**
713 * Compute the julian day number of the day BEFORE the first day of
714 * January 1, year 1 of the given calendar.  If julianDay == 0, it
715 * specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
716 * or Gregorian).
717 */
computeJulianDayOfYear(UBool isGregorian,int32_t year,UBool & isLeap)718 double GregorianCalendar::computeJulianDayOfYear(UBool isGregorian,
719                                                  int32_t year, UBool& isLeap)
720 {
721     isLeap = year%4 == 0;
722     int32_t y = year - 1;
723     double julianDay = 365.0*y + ClockMath::floorDivide(y, 4) + (kJan1_1JulianDay - 3);
724 
725     if (isGregorian) {
726         isLeap = isLeap && ((year%100 != 0) || (year%400 == 0));
727         // Add 2 because Gregorian calendar starts 2 days after Julian calendar
728         julianDay += Grego::gregorianShift(year);
729     }
730 
731     return julianDay;
732 }
733 
734 // /**
735 //  * Compute the day of week, relative to the first day of week, from
736 //  * 0..6, of the current DOW_LOCAL or DAY_OF_WEEK fields.  This is
737 //  * equivalent to get(DOW_LOCAL) - 1.
738 //  */
739 // int32_t GregorianCalendar::computeRelativeDOW() const {
740 //     int32_t relDow = 0;
741 //     if (fStamp[UCAL_DOW_LOCAL] > fStamp[UCAL_DAY_OF_WEEK]) {
742 //         relDow = internalGet(UCAL_DOW_LOCAL) - 1; // 1-based
743 //     } else if (fStamp[UCAL_DAY_OF_WEEK] != kUnset) {
744 //         relDow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
745 //         if (relDow < 0) relDow += 7;
746 //     }
747 //     return relDow;
748 // }
749 
750 // /**
751 //  * Compute the day of week, relative to the first day of week,
752 //  * from 0..6 of the given julian day.
753 //  */
754 // int32_t GregorianCalendar::computeRelativeDOW(double julianDay) const {
755 //   int32_t relDow = julianDayToDayOfWeek(julianDay) - getFirstDayOfWeek();
756 //     if (relDow < 0) {
757 //         relDow += 7;
758 //     }
759 //     return relDow;
760 // }
761 
762 // /**
763 //  * Compute the DOY using the WEEK_OF_YEAR field and the julian day
764 //  * of the day BEFORE January 1 of a year (a return value from
765 //  * computeJulianDayOfYear).
766 //  */
767 // int32_t GregorianCalendar::computeDOYfromWOY(double julianDayOfYear) const {
768 //     // Compute DOY from day of week plus week of year
769 
770 //     // Find the day of the week for the first of this year.  This
771 //     // is zero-based, with 0 being the locale-specific first day of
772 //     // the week.  Add 1 to get first day of year.
773 //     int32_t fdy = computeRelativeDOW(julianDayOfYear + 1);
774 
775 //     return
776 //         // Compute doy of first (relative) DOW of WOY 1
777 //         (((7 - fdy) < getMinimalDaysInFirstWeek())
778 //          ? (8 - fdy) : (1 - fdy))
779 
780 //         // Adjust for the week number.
781 //         + (7 * (internalGet(UCAL_WEEK_OF_YEAR) - 1))
782 
783 //         // Adjust for the DOW
784 //         + computeRelativeDOW();
785 // }
786 
787 // -------------------------------------
788 
789 double
millisToJulianDay(UDate millis)790 GregorianCalendar::millisToJulianDay(UDate millis)
791 {
792     return (double)kEpochStartAsJulianDay + ClockMath::floorDivide(millis, (double)kOneDay);
793 }
794 
795 // -------------------------------------
796 
797 UDate
julianDayToMillis(double julian)798 GregorianCalendar::julianDayToMillis(double julian)
799 {
800     return (UDate) ((julian - kEpochStartAsJulianDay) * (double) kOneDay);
801 }
802 
803 // -------------------------------------
804 
805 int32_t
aggregateStamp(int32_t stamp_a,int32_t stamp_b)806 GregorianCalendar::aggregateStamp(int32_t stamp_a, int32_t stamp_b)
807 {
808     return (((stamp_a != kUnset && stamp_b != kUnset)
809         ? uprv_max(stamp_a, stamp_b)
810         : (int32_t)kUnset));
811 }
812 
813 // -------------------------------------
814 
815 /**
816 * Roll a field by a signed amount.
817 * Note: This will be made public later. [LIU]
818 */
819 
820 void
roll(EDateFields field,int32_t amount,UErrorCode & status)821 GregorianCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) {
822     roll((UCalendarDateFields) field, amount, status);
823 }
824 
825 void
roll(UCalendarDateFields field,int32_t amount,UErrorCode & status)826 GregorianCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) UPRV_NO_SANITIZE_UNDEFINED {
827     if((amount == 0) || U_FAILURE(status)) {
828         return;
829     }
830 
831     // J81 processing. (gregorian cutover)
832     UBool inCutoverMonth = false;
833     int32_t cMonthLen=0; // 'c' for cutover; in days
834     int32_t cDayOfMonth=0; // no discontinuity: [0, cMonthLen)
835     double cMonthStart=0.0; // in ms
836 
837     // Common code - see if we're in the cutover month of the cutover year
838     if(get(UCAL_EXTENDED_YEAR, status) == fGregorianCutoverYear) {
839         switch (field) {
840         case UCAL_DAY_OF_MONTH:
841         case UCAL_WEEK_OF_MONTH:
842             {
843                 int32_t max = monthLength(internalGetMonth());
844                 UDate t = internalGetTime();
845                 // We subtract 1 from the DAY_OF_MONTH to make it zero-based, and an
846                 // additional 10 if we are after the cutover. Thus the monthStart
847                 // value will be correct iff we actually are in the cutover month.
848                 cDayOfMonth = internalGet(UCAL_DAY_OF_MONTH) - ((t >= fGregorianCutover) ? 10 : 0);
849                 cMonthStart = t - ((cDayOfMonth - 1) * kOneDay);
850                 // A month containing the cutover is 10 days shorter.
851                 if ((cMonthStart < fGregorianCutover) &&
852                     (cMonthStart + (cMonthLen=(max-10))*kOneDay >= fGregorianCutover)) {
853                         inCutoverMonth = true;
854                     }
855             }
856             break;
857         default:
858             ;
859         }
860     }
861 
862     switch (field) {
863     case UCAL_WEEK_OF_YEAR: {
864         // Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the
865         // week.  Also, rolling the week of the year can have seemingly
866         // strange effects simply because the year of the week of year
867         // may be different from the calendar year.  For example, the
868         // date Dec 28, 1997 is the first day of week 1 of 1998 (if
869         // weeks start on Sunday and the minimal days in first week is
870         // <= 3).
871         int32_t woy = get(UCAL_WEEK_OF_YEAR, status);
872         // Get the ISO year, which matches the week of year.  This
873         // may be one year before or after the calendar year.
874         int32_t isoYear = get(UCAL_YEAR_WOY, status);
875         int32_t isoDoy = internalGet(UCAL_DAY_OF_YEAR);
876         if (internalGetMonth() == UCAL_JANUARY) {
877             if (woy >= 52) {
878                 isoDoy += handleGetYearLength(isoYear);
879             }
880         } else {
881             if (woy == 1) {
882                 isoDoy -= handleGetYearLength(isoYear - 1);
883             }
884         }
885         woy += amount;
886         // Do fast checks to avoid unnecessary computation:
887         if (woy < 1 || woy > 52) {
888             // Determine the last week of the ISO year.
889             // We do this using the standard formula we use
890             // everywhere in this file.  If we can see that the
891             // days at the end of the year are going to fall into
892             // week 1 of the next year, we drop the last week by
893             // subtracting 7 from the last day of the year.
894             int32_t lastDoy = handleGetYearLength(isoYear);
895             int32_t lastRelDow = (lastDoy - isoDoy + internalGet(UCAL_DAY_OF_WEEK) -
896                 getFirstDayOfWeek()) % 7;
897             if (lastRelDow < 0) lastRelDow += 7;
898             if ((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) lastDoy -= 7;
899             int32_t lastWoy = weekNumber(lastDoy, lastRelDow + 1);
900             woy = ((woy + lastWoy - 1) % lastWoy) + 1;
901         }
902         set(UCAL_WEEK_OF_YEAR, woy);
903         set(UCAL_YEAR_WOY,isoYear);
904         return;
905                             }
906 
907     case UCAL_DAY_OF_MONTH:
908         if( !inCutoverMonth ) {
909             Calendar::roll(field, amount, status);
910             return;
911         } else {
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         } else {
935 #if defined (U_DEBUG_CAL)
936             fprintf(stderr, "%s:%d: roll WOM %d ??????????????????? \n",
937                 __FILE__, __LINE__,amount);
938 #endif
939             // NOTE: following copied from  the old
940             //     GregorianCalendar::roll( WEEK_OF_MONTH )  code
941 
942             // This is tricky, because during the roll we may have to shift
943             // to a different day of the week.  For example:
944 
945             //    s  m  t  w  r  f  s
946             //          1  2  3  4  5
947             //    6  7  8  9 10 11 12
948 
949             // When rolling from the 6th or 7th back one week, we go to the
950             // 1st (assuming that the first partial week counts).  The same
951             // thing happens at the end of the month.
952 
953             // The other tricky thing is that we have to figure out whether
954             // the first partial week actually counts or not, based on the
955             // minimal first days in the week.  And we have to use the
956             // correct first day of the week to delineate the week
957             // boundaries.
958 
959             // Here's our algorithm.  First, we find the real boundaries of
960             // the month.  Then we discard the first partial week if it
961             // doesn't count in this locale.  Then we fill in the ends with
962             // phantom days, so that the first partial week and the last
963             // partial week are full weeks.  We then have a nice square
964             // block of weeks.  We do the usual rolling within this block,
965             // as is done elsewhere in this method.  If we wind up on one of
966             // the phantom days that we added, we recognize this and pin to
967             // the first or the last day of the month.  Easy, eh?
968 
969             // Another wrinkle: To fix jitterbug 81, we have to make all this
970             // work in the oddball month containing the Gregorian cutover.
971             // This month is 10 days shorter than usual, and also contains
972             // a discontinuity in the days; e.g., the default cutover month
973             // is Oct 1582, and goes from day of month 4 to day of month 15.
974 
975             // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
976             // in this locale.  We have dow in 0..6.
977             int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
978             if (dow < 0)
979                 dow += 7;
980 
981             // Find the day of month, compensating for cutover discontinuity.
982             int32_t dom = cDayOfMonth;
983 
984             // Find the day of the week (normalized for locale) for the first
985             // of the month.
986             int32_t fdm = (dow - dom + 1) % 7;
987             if (fdm < 0)
988                 fdm += 7;
989 
990             // Get the first day of the first full week of the month,
991             // including phantom days, if any.  Figure out if the first week
992             // counts or not; if it counts, then fill in phantom days.  If
993             // not, advance to the first real full week (skip the partial week).
994             int32_t start;
995             if ((7 - fdm) < getMinimalDaysInFirstWeek())
996                 start = 8 - fdm; // Skip the first partial week
997             else
998                 start = 1 - fdm; // This may be zero or negative
999 
1000             // Get the day of the week (normalized for locale) for the last
1001             // day of the month.
1002             int32_t monthLen = cMonthLen;
1003             int32_t ldm = (monthLen - dom + dow) % 7;
1004             // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here.
1005 
1006             // Get the limit day for the blocked-off rectangular month; that
1007             // is, the day which is one past the last day of the month,
1008             // after the month has already been filled in with phantom days
1009             // to fill out the last week.  This day has a normalized DOW of 0.
1010             int32_t limit = monthLen + 7 - ldm;
1011 
1012             // Now roll between start and (limit - 1).
1013             int32_t gap = limit - start;
1014             int32_t newDom = (dom + amount*7 - start) % gap;
1015             if (newDom < 0)
1016                 newDom += gap;
1017             newDom += start;
1018 
1019             // Finally, pin to the real start and end of the month.
1020             if (newDom < 1)
1021                 newDom = 1;
1022             if (newDom > monthLen)
1023                 newDom = monthLen;
1024 
1025             // Set the DAY_OF_MONTH.  We rely on the fact that this field
1026             // takes precedence over everything else (since all other fields
1027             // are also set at this point).  If this fact changes (if the
1028             // disambiguation algorithm changes) then we will have to unset
1029             // the appropriate fields here so that DAY_OF_MONTH is attended
1030             // to.
1031 
1032             // If we are in the cutover month, manipulate ms directly.  Don't do
1033             // this in general because it doesn't work across DST boundaries
1034             // (details, details).  This takes care of the discontinuity.
1035             setTimeInMillis(cMonthStart + (newDom-1)*kOneDay, status);
1036             return;
1037         }
1038 
1039     default:
1040         Calendar::roll(field, amount, status);
1041         return;
1042     }
1043 }
1044 
1045 // -------------------------------------
1046 
1047 
1048 /**
1049 * Return the minimum value that this field could have, given the current date.
1050 * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
1051 * @param field    the time field.
1052 * @return         the minimum value that this field could have, given the current date.
1053 * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead.
1054 */
getActualMinimum(EDateFields field) const1055 int32_t GregorianCalendar::getActualMinimum(EDateFields field) const
1056 {
1057     return getMinimum((UCalendarDateFields)field);
1058 }
1059 
getActualMinimum(EDateFields field,UErrorCode &) const1060 int32_t GregorianCalendar::getActualMinimum(EDateFields field, UErrorCode& /* status */) const
1061 {
1062     return getMinimum((UCalendarDateFields)field);
1063 }
1064 
1065 /**
1066 * Return the minimum value that this field could have, given the current date.
1067 * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
1068 * @param field    the time field.
1069 * @return         the minimum value that this field could have, given the current date.
1070 * @draft ICU 2.6.
1071 */
getActualMinimum(UCalendarDateFields field,UErrorCode &) const1072 int32_t GregorianCalendar::getActualMinimum(UCalendarDateFields field, UErrorCode& /* status */) const
1073 {
1074     return getMinimum(field);
1075 }
1076 
1077 
1078 // ------------------------------------
1079 
1080 /**
1081 * Old year limits were least max 292269054, max 292278994.
1082 */
1083 
1084 /**
1085 * @stable ICU 2.0
1086 */
handleGetLimit(UCalendarDateFields field,ELimitType limitType) const1087 int32_t GregorianCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const {
1088     return kGregorianCalendarLimits[field][limitType];
1089 }
1090 
1091 /**
1092 * Return the maximum value that this field could have, given the current date.
1093 * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
1094 * maximum would be 28; for "Feb 3, 1996" it s 29.  Similarly for a Hebrew calendar,
1095 * for some years the actual maximum for MONTH is 12, and for others 13.
1096 * @stable ICU 2.0
1097 */
getActualMaximum(UCalendarDateFields field,UErrorCode & status) const1098 int32_t GregorianCalendar::getActualMaximum(UCalendarDateFields field, UErrorCode& status) const
1099 {
1100     /* It is a known limitation that the code here (and in getActualMinimum)
1101     * won't behave properly at the extreme limits of GregorianCalendar's
1102     * representable range (except for the code that handles the YEAR
1103     * field).  That's because the ends of the representable range are at
1104     * odd spots in the year.  For calendars with the default Gregorian
1105     * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun
1106     * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT
1107     * zones.  As a result, if the calendar is set to Aug 1 292278994 AD,
1108     * the actual maximum of DAY_OF_MONTH is 17, not 30.  If the date is Mar
1109     * 31 in that year, the actual maximum month might be Jul, whereas is
1110     * the date is Mar 15, the actual maximum might be Aug -- depending on
1111     * the precise semantics that are desired.  Similar considerations
1112     * affect all fields.  Nonetheless, this effect is sufficiently arcane
1113     * that we permit it, rather than complicating the code to handle such
1114     * intricacies. - liu 8/20/98
1115 
1116     * UPDATE: No longer true, since we have pulled in the limit values on
1117     * the year. - Liu 11/6/00 */
1118 
1119     switch (field) {
1120 
1121     case UCAL_YEAR:
1122         /* The year computation is no different, in principle, from the
1123         * others, however, the range of possible maxima is large.  In
1124         * addition, the way we know we've exceeded the range is different.
1125         * For these reasons, we use the special case code below to handle
1126         * this field.
1127         *
1128         * The actual maxima for YEAR depend on the type of calendar:
1129         *
1130         *     Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD
1131         *     Julian    = Dec  2, 292269055 BC - Jan  3, 292272993 AD
1132         *     Hybrid    = Dec  2, 292269055 BC - Aug 17, 292278994 AD
1133         *
1134         * We know we've exceeded the maximum when either the month, date,
1135         * time, or era changes in response to setting the year.  We don't
1136         * check for month, date, and time here because the year and era are
1137         * sufficient to detect an invalid year setting.  NOTE: If code is
1138         * added to check the month and date in the future for some reason,
1139         * Feb 29 must be allowed to shift to Mar 1 when setting the year.
1140         */
1141         {
1142             if(U_FAILURE(status)) return 0;
1143             Calendar *cal = clone();
1144             if(!cal) {
1145                 status = U_MEMORY_ALLOCATION_ERROR;
1146                 return 0;
1147             }
1148 
1149             cal->setLenient(true);
1150 
1151             int32_t era = cal->get(UCAL_ERA, status);
1152             UDate d = cal->getTime(status);
1153 
1154             /* Perform a binary search, with the invariant that lowGood is a
1155             * valid year, and highBad is an out of range year.
1156             */
1157             int32_t lowGood = kGregorianCalendarLimits[UCAL_YEAR][1];
1158             int32_t highBad = kGregorianCalendarLimits[UCAL_YEAR][2]+1;
1159             while ((lowGood + 1) < highBad) {
1160                 int32_t y = (lowGood + highBad) / 2;
1161                 cal->set(UCAL_YEAR, y);
1162                 if (cal->get(UCAL_YEAR, status) == y && cal->get(UCAL_ERA, status) == era) {
1163                     lowGood = y;
1164                 } else {
1165                     highBad = y;
1166                     cal->setTime(d, status); // Restore original fields
1167                 }
1168             }
1169 
1170             delete cal;
1171             return lowGood;
1172         }
1173 
1174     default:
1175         return Calendar::getActualMaximum(field,status);
1176     }
1177 }
1178 
1179 
handleGetExtendedYear()1180 int32_t GregorianCalendar::handleGetExtendedYear() {
1181     // the year to return
1182     int32_t year = kEpochYear;
1183 
1184     // year field to use
1185     int32_t yearField = UCAL_EXTENDED_YEAR;
1186 
1187     // There are three separate fields which could be used to
1188     // derive the proper year.  Use the one most recently set.
1189     if (fStamp[yearField] < fStamp[UCAL_YEAR])
1190         yearField = UCAL_YEAR;
1191     if (fStamp[yearField] < fStamp[UCAL_YEAR_WOY])
1192         yearField = UCAL_YEAR_WOY;
1193 
1194     // based on the "best" year field, get the year
1195     switch(yearField) {
1196     case UCAL_EXTENDED_YEAR:
1197         year = internalGet(UCAL_EXTENDED_YEAR, kEpochYear);
1198         break;
1199 
1200     case UCAL_YEAR:
1201         {
1202             // The year defaults to the epoch start, the era to AD
1203             int32_t era = internalGet(UCAL_ERA, AD);
1204             if (era == BC) {
1205                 year = 1 - internalGet(UCAL_YEAR, 1); // Convert to extended year
1206             } else {
1207                 year = internalGet(UCAL_YEAR, kEpochYear);
1208             }
1209         }
1210         break;
1211 
1212     case UCAL_YEAR_WOY:
1213         year = handleGetExtendedYearFromWeekFields(internalGet(UCAL_YEAR_WOY), internalGet(UCAL_WEEK_OF_YEAR));
1214 #if defined (U_DEBUG_CAL)
1215         //    if(internalGet(UCAL_YEAR_WOY) != year) {
1216         fprintf(stderr, "%s:%d: hGEYFWF[%d,%d] ->  %d\n",
1217             __FILE__, __LINE__,internalGet(UCAL_YEAR_WOY),internalGet(UCAL_WEEK_OF_YEAR),year);
1218         //}
1219 #endif
1220         break;
1221 
1222     default:
1223         year = kEpochYear;
1224     }
1225     return year;
1226 }
1227 
handleGetExtendedYearFromWeekFields(int32_t yearWoy,int32_t woy)1228 int32_t GregorianCalendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy)
1229 {
1230     // convert year to extended form
1231     int32_t era = internalGet(UCAL_ERA, AD);
1232     if(era == BC) {
1233         yearWoy = 1 - yearWoy;
1234     }
1235     return Calendar::handleGetExtendedYearFromWeekFields(yearWoy, woy);
1236 }
1237 
1238 
1239 // -------------------------------------
1240 
1241 /**
1242 * Return the ERA.  We need a special method for this because the
1243 * default ERA is AD, but a zero (unset) ERA is BC.
1244 */
1245 int32_t
internalGetEra() const1246 GregorianCalendar::internalGetEra() const {
1247     return isSet(UCAL_ERA) ? internalGet(UCAL_ERA) : (int32_t)AD;
1248 }
1249 
1250 const char *
getType() const1251 GregorianCalendar::getType() const {
1252     //static const char kGregorianType = "gregorian";
1253 
1254     return "gregorian";
1255 }
1256 
1257 /**
1258  * The system maintains a static default century start date and Year.  They are
1259  * initialized the first time they are used.  Once the system default century date
1260  * and year are set, they do not change.
1261  */
1262 static UDate           gSystemDefaultCenturyStart       = DBL_MIN;
1263 static int32_t         gSystemDefaultCenturyStartYear   = -1;
1264 static icu::UInitOnce  gSystemDefaultCenturyInit        {};
1265 
1266 
haveDefaultCentury() const1267 UBool GregorianCalendar::haveDefaultCentury() const
1268 {
1269     return true;
1270 }
1271 
1272 static void U_CALLCONV
initializeSystemDefaultCentury()1273 initializeSystemDefaultCentury()
1274 {
1275     // initialize systemDefaultCentury and systemDefaultCenturyYear based
1276     // on the current time.  They'll be set to 80 years before
1277     // the current time.
1278     UErrorCode status = U_ZERO_ERROR;
1279     GregorianCalendar calendar(status);
1280     if (U_SUCCESS(status)) {
1281         calendar.setTime(Calendar::getNow(), status);
1282         calendar.add(UCAL_YEAR, -80, status);
1283 
1284         gSystemDefaultCenturyStart = calendar.getTime(status);
1285         gSystemDefaultCenturyStartYear = calendar.get(UCAL_YEAR, status);
1286     }
1287     // We have no recourse upon failure unless we want to propagate the failure
1288     // out.
1289 }
1290 
defaultCenturyStart() const1291 UDate GregorianCalendar::defaultCenturyStart() const {
1292     // lazy-evaluate systemDefaultCenturyStart
1293     umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury);
1294     return gSystemDefaultCenturyStart;
1295 }
1296 
defaultCenturyStartYear() const1297 int32_t GregorianCalendar::defaultCenturyStartYear() const {
1298     // lazy-evaluate systemDefaultCenturyStartYear
1299     umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury);
1300     return gSystemDefaultCenturyStartYear;
1301 }
1302 
1303 U_NAMESPACE_END
1304 
1305 #endif /* #if !UCONFIG_NO_FORMATTING */
1306 
1307 //eof
1308