• 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) 2007-2014, International Business Machines Corporation
6  * and others. All Rights Reserved.
7  ******************************************************************************
8  *
9  * File CHNSECAL.CPP
10  *
11  * Modification History:
12  *
13  *   Date        Name        Description
14  *   9/18/2007  ajmacher         ported from java ChineseCalendar
15  *****************************************************************************
16  */
17 
18 #include "chnsecal.h"
19 
20 #if !UCONFIG_NO_FORMATTING
21 
22 #include "umutex.h"
23 #include <float.h>
24 #include "gregoimp.h" // Math
25 #include "astro.h" // CalendarAstronomer
26 #include "unicode/simpletz.h"
27 #include "uhash.h"
28 #include "ucln_in.h"
29 #include "cstring.h"
30 
31 // Debugging
32 #ifdef U_DEBUG_CHNSECAL
33 # include <stdio.h>
34 # include <stdarg.h>
debug_chnsecal_loc(const char * f,int32_t l)35 static void debug_chnsecal_loc(const char *f, int32_t l)
36 {
37     fprintf(stderr, "%s:%d: ", f, l);
38 }
39 
debug_chnsecal_msg(const char * pat,...)40 static void debug_chnsecal_msg(const char *pat, ...)
41 {
42     va_list ap;
43     va_start(ap, pat);
44     vfprintf(stderr, pat, ap);
45     fflush(stderr);
46 }
47 // must use double parens, i.e.:  U_DEBUG_CHNSECAL_MSG(("four is: %d",4));
48 #define U_DEBUG_CHNSECAL_MSG(x) {debug_chnsecal_loc(__FILE__,__LINE__);debug_chnsecal_msg x;}
49 #else
50 #define U_DEBUG_CHNSECAL_MSG(x)
51 #endif
52 
53 
54 // --- The cache --
55 static icu::UMutex astroLock;
56 static icu::CalendarAstronomer *gChineseCalendarAstro = nullptr;
57 
58 // Lazy Creation & Access synchronized by class CalendarCache with a mutex.
59 static icu::CalendarCache *gChineseCalendarWinterSolsticeCache = nullptr;
60 static icu::CalendarCache *gChineseCalendarNewYearCache = nullptr;
61 
62 static icu::TimeZone *gChineseCalendarZoneAstroCalc = nullptr;
63 static icu::UInitOnce gChineseCalendarZoneAstroCalcInitOnce {};
64 
65 /**
66  * The start year of the Chinese calendar, the 61st year of the reign
67  * of Huang Di.  Some sources use the first year of his reign,
68  * resulting in EXTENDED_YEAR values 60 years greater and ERA (cycle)
69  * values one greater.
70  */
71 static const int32_t CHINESE_EPOCH_YEAR = -2636; // Gregorian year
72 
73 /**
74  * The offset from GMT in milliseconds at which we perform astronomical
75  * computations.  Some sources use a different historically accurate
76  * offset of GMT+7:45:40 for years before 1929; we do not do this.
77  */
78 static const int32_t CHINA_OFFSET = 8 * kOneHour;
79 
80 /**
81  * Value to be added or subtracted from the local days of a new moon to
82  * get close to the next or prior new moon, but not cross it.  Must be
83  * >= 1 and < CalendarAstronomer.SYNODIC_MONTH.
84  */
85 static const int32_t SYNODIC_GAP = 25;
86 
87 
88 U_CDECL_BEGIN
calendar_chinese_cleanup()89 static UBool calendar_chinese_cleanup() {
90     if (gChineseCalendarAstro) {
91         delete gChineseCalendarAstro;
92         gChineseCalendarAstro = nullptr;
93     }
94     if (gChineseCalendarWinterSolsticeCache) {
95         delete gChineseCalendarWinterSolsticeCache;
96         gChineseCalendarWinterSolsticeCache = nullptr;
97     }
98     if (gChineseCalendarNewYearCache) {
99         delete gChineseCalendarNewYearCache;
100         gChineseCalendarNewYearCache = nullptr;
101     }
102     if (gChineseCalendarZoneAstroCalc) {
103         delete gChineseCalendarZoneAstroCalc;
104         gChineseCalendarZoneAstroCalc = nullptr;
105     }
106     gChineseCalendarZoneAstroCalcInitOnce.reset();
107     return true;
108 }
109 U_CDECL_END
110 
111 U_NAMESPACE_BEGIN
112 
113 
114 // Implementation of the ChineseCalendar class
115 
116 
117 //-------------------------------------------------------------------------
118 // Constructors...
119 //-------------------------------------------------------------------------
120 
121 
clone() const122 ChineseCalendar* ChineseCalendar::clone() const {
123     return new ChineseCalendar(*this);
124 }
125 
ChineseCalendar(const Locale & aLocale,UErrorCode & success)126 ChineseCalendar::ChineseCalendar(const Locale& aLocale, UErrorCode& success)
127 :   Calendar(TimeZone::forLocaleOrDefault(aLocale), aLocale, success),
128     hasLeapMonthBetweenWinterSolstices(false),
129     fEpochYear(CHINESE_EPOCH_YEAR),
130     fZoneAstroCalc(getChineseCalZoneAstroCalc())
131 {
132     setTimeInMillis(getNow(), success); // Call this again now that the vtable is set up properly.
133 }
134 
ChineseCalendar(const Locale & aLocale,int32_t epochYear,const TimeZone * zoneAstroCalc,UErrorCode & success)135 ChineseCalendar::ChineseCalendar(const Locale& aLocale, int32_t epochYear,
136                                 const TimeZone* zoneAstroCalc, UErrorCode &success)
137 :   Calendar(TimeZone::forLocaleOrDefault(aLocale), aLocale, success),
138     hasLeapMonthBetweenWinterSolstices(false),
139     fEpochYear(epochYear),
140     fZoneAstroCalc(zoneAstroCalc)
141 {
142     setTimeInMillis(getNow(), success); // Call this again now that the vtable is set up properly.
143 }
144 
ChineseCalendar(const ChineseCalendar & other)145 ChineseCalendar::ChineseCalendar(const ChineseCalendar& other) : Calendar(other) {
146     hasLeapMonthBetweenWinterSolstices = other.hasLeapMonthBetweenWinterSolstices;
147     fEpochYear = other.fEpochYear;
148     fZoneAstroCalc = other.fZoneAstroCalc;
149 }
150 
~ChineseCalendar()151 ChineseCalendar::~ChineseCalendar()
152 {
153 }
154 
getType() const155 const char *ChineseCalendar::getType() const {
156     return "chinese";
157 }
158 
initChineseCalZoneAstroCalc()159 static void U_CALLCONV initChineseCalZoneAstroCalc() {
160     gChineseCalendarZoneAstroCalc = new SimpleTimeZone(CHINA_OFFSET, UNICODE_STRING_SIMPLE("CHINA_ZONE") );
161     ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR, calendar_chinese_cleanup);
162 }
163 
getChineseCalZoneAstroCalc() const164 const TimeZone* ChineseCalendar::getChineseCalZoneAstroCalc() const {
165     umtx_initOnce(gChineseCalendarZoneAstroCalcInitOnce, &initChineseCalZoneAstroCalc);
166     return gChineseCalendarZoneAstroCalc;
167 }
168 
169 //-------------------------------------------------------------------------
170 // Minimum / Maximum access functions
171 //-------------------------------------------------------------------------
172 
173 
174 static const int32_t LIMITS[UCAL_FIELD_COUNT][4] = {
175     // Minimum  Greatest     Least    Maximum
176     //           Minimum   Maximum
177     {        1,        1,    83333,    83333}, // ERA
178     {        1,        1,       60,       60}, // YEAR
179     {        0,        0,       11,       11}, // MONTH
180     {        1,        1,       50,       55}, // WEEK_OF_YEAR
181     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // WEEK_OF_MONTH
182     {        1,        1,       29,       30}, // DAY_OF_MONTH
183     {        1,        1,      353,      385}, // DAY_OF_YEAR
184     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK
185     {       -1,       -1,        5,        5}, // DAY_OF_WEEK_IN_MONTH
186     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM
187     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR
188     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY
189     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE
190     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND
191     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND
192     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET
193     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET
194     { -5000000, -5000000,  5000000,  5000000}, // YEAR_WOY
195     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL
196     { -5000000, -5000000,  5000000,  5000000}, // EXTENDED_YEAR
197     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY
198     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECONDS_IN_DAY
199     {        0,        0,        1,        1}, // IS_LEAP_MONTH
200     {        0,        0,       11,       12}, // ORDINAL_MONTH
201 };
202 
203 
204 /**
205 * @draft ICU 2.4
206 */
handleGetLimit(UCalendarDateFields field,ELimitType limitType) const207 int32_t ChineseCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const {
208     return LIMITS[field][limitType];
209 }
210 
211 
212 //----------------------------------------------------------------------
213 // Calendar framework
214 //----------------------------------------------------------------------
215 
216 /**
217  * Implement abstract Calendar method to return the extended year
218  * defined by the current fields.  This will use either the ERA and
219  * YEAR field as the cycle and year-of-cycle, or the EXTENDED_YEAR
220  * field as the continuous year count, depending on which is newer.
221  * @stable ICU 2.8
222  */
handleGetExtendedYear()223 int32_t ChineseCalendar::handleGetExtendedYear() {
224     int32_t year;
225     if (newestStamp(UCAL_ERA, UCAL_YEAR, kUnset) <= fStamp[UCAL_EXTENDED_YEAR]) {
226         year = internalGet(UCAL_EXTENDED_YEAR, 1); // Default to year 1
227     } else {
228         int32_t cycle = internalGet(UCAL_ERA, 1) - 1; // 0-based cycle
229         // adjust to the instance specific epoch
230         year = cycle * 60 + internalGet(UCAL_YEAR, 1) - (fEpochYear - CHINESE_EPOCH_YEAR);
231     }
232     return year;
233 }
234 
235 /**
236  * Override Calendar method to return the number of days in the given
237  * extended year and month.
238  *
239  * <p>Note: This method also reads the IS_LEAP_MONTH field to determine
240  * whether or not the given month is a leap month.
241  * @stable ICU 2.8
242  */
handleGetMonthLength(int32_t extendedYear,int32_t month) const243 int32_t ChineseCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month) const {
244     int32_t thisStart = handleComputeMonthStart(extendedYear, month, true) -
245         kEpochStartAsJulianDay + 1; // Julian day -> local days
246     int32_t nextStart = newMoonNear(thisStart + SYNODIC_GAP, true);
247     return nextStart - thisStart;
248 }
249 
250 /**
251  * Override Calendar to compute several fields specific to the Chinese
252  * calendar system.  These are:
253  *
254  * <ul><li>ERA
255  * <li>YEAR
256  * <li>MONTH
257  * <li>DAY_OF_MONTH
258  * <li>DAY_OF_YEAR
259  * <li>EXTENDED_YEAR</ul>
260  *
261  * The DAY_OF_WEEK and DOW_LOCAL fields are already set when this
262  * method is called.  The getGregorianXxx() methods return Gregorian
263  * calendar equivalents for the given Julian day.
264  *
265  * <p>Compute the ChineseCalendar-specific field IS_LEAP_MONTH.
266  * @stable ICU 2.8
267  */
handleComputeFields(int32_t julianDay,UErrorCode &)268 void ChineseCalendar::handleComputeFields(int32_t julianDay, UErrorCode &/*status*/) {
269 
270     computeChineseFields(julianDay - kEpochStartAsJulianDay, // local days
271                          getGregorianYear(), getGregorianMonth(),
272                          true); // set all fields
273 }
274 
275 /**
276  * Field resolution table that incorporates IS_LEAP_MONTH.
277  */
278 const UFieldResolutionTable ChineseCalendar::CHINESE_DATE_PRECEDENCE[] =
279 {
280     {
281         { UCAL_DAY_OF_MONTH, kResolveSTOP },
282         { UCAL_WEEK_OF_YEAR, UCAL_DAY_OF_WEEK, kResolveSTOP },
283         { UCAL_WEEK_OF_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP },
284         { UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP },
285         { UCAL_WEEK_OF_YEAR, UCAL_DOW_LOCAL, kResolveSTOP },
286         { UCAL_WEEK_OF_MONTH, UCAL_DOW_LOCAL, kResolveSTOP },
287         { UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP },
288         { UCAL_DAY_OF_YEAR, kResolveSTOP },
289         { kResolveRemap | UCAL_DAY_OF_MONTH, UCAL_IS_LEAP_MONTH, kResolveSTOP },
290         { kResolveSTOP }
291     },
292     {
293         { UCAL_WEEK_OF_YEAR, kResolveSTOP },
294         { UCAL_WEEK_OF_MONTH, kResolveSTOP },
295         { UCAL_DAY_OF_WEEK_IN_MONTH, kResolveSTOP },
296         { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP },
297         { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP },
298         { kResolveSTOP }
299     },
300     {{kResolveSTOP}}
301 };
302 
303 /**
304  * Override Calendar to add IS_LEAP_MONTH to the field resolution
305  * table.
306  * @stable ICU 2.8
307  */
getFieldResolutionTable() const308 const UFieldResolutionTable* ChineseCalendar::getFieldResolutionTable() const {
309     return CHINESE_DATE_PRECEDENCE;
310 }
311 
312 /**
313  * Return the Julian day number of day before the first day of the
314  * given month in the given extended year.
315  *
316  * <p>Note: This method reads the IS_LEAP_MONTH field to determine
317  * whether the given month is a leap month.
318  * @param eyear the extended year
319  * @param month the zero-based month.  The month is also determined
320  * by reading the IS_LEAP_MONTH field.
321  * @return the Julian day number of the day before the first
322  * day of the given month and year
323  * @stable ICU 2.8
324  */
handleComputeMonthStart(int32_t eyear,int32_t month,UBool useMonth) const325 int32_t ChineseCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool useMonth) const {
326     ChineseCalendar *nonConstThis = (ChineseCalendar*)this; // cast away const
327 
328     // If the month is out of range, adjust it into range, and
329     // modify the extended year value accordingly.
330     if (month < 0 || month > 11) {
331         double m = month;
332         eyear += (int32_t)ClockMath::floorDivide(m, 12.0, &m);
333         month = (int32_t)m;
334     }
335 
336     int32_t gyear = eyear + fEpochYear - 1; // Gregorian year
337     int32_t theNewYear = newYear(gyear);
338     int32_t newMoon = newMoonNear(theNewYear + month * 29, true);
339 
340     int32_t julianDay = newMoon + kEpochStartAsJulianDay;
341 
342     // Save fields for later restoration
343     int32_t saveMonth = internalGet(UCAL_MONTH);
344     int32_t saveOrdinalMonth = internalGet(UCAL_ORDINAL_MONTH);
345     int32_t saveIsLeapMonth = internalGet(UCAL_IS_LEAP_MONTH);
346 
347     // Ignore IS_LEAP_MONTH field if useMonth is false
348     int32_t isLeapMonth = useMonth ? saveIsLeapMonth : 0;
349 
350     UErrorCode status = U_ZERO_ERROR;
351     nonConstThis->computeGregorianFields(julianDay, status);
352     if (U_FAILURE(status))
353         return 0;
354 
355     // This will modify the MONTH and IS_LEAP_MONTH fields (only)
356     nonConstThis->computeChineseFields(newMoon, getGregorianYear(),
357                          getGregorianMonth(), false);
358 
359     if (month != internalGet(UCAL_MONTH) ||
360         isLeapMonth != internalGet(UCAL_IS_LEAP_MONTH)) {
361         newMoon = newMoonNear(newMoon + SYNODIC_GAP, true);
362         julianDay = newMoon + kEpochStartAsJulianDay;
363     }
364 
365     nonConstThis->internalSet(UCAL_MONTH, saveMonth);
366     nonConstThis->internalSet(UCAL_ORDINAL_MONTH, saveOrdinalMonth);
367     nonConstThis->internalSet(UCAL_IS_LEAP_MONTH, saveIsLeapMonth);
368     return julianDay - 1;
369 }
370 
371 
372 /**
373  * Override Calendar to handle leap months properly.
374  * @stable ICU 2.8
375  */
add(UCalendarDateFields field,int32_t amount,UErrorCode & status)376 void ChineseCalendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& status) {
377     switch (field) {
378     case UCAL_MONTH:
379     case UCAL_ORDINAL_MONTH:
380         if (amount != 0) {
381             int32_t dom = get(UCAL_DAY_OF_MONTH, status);
382             if (U_FAILURE(status)) break;
383             int32_t day = get(UCAL_JULIAN_DAY, status) - kEpochStartAsJulianDay; // Get local day
384             if (U_FAILURE(status)) break;
385             int32_t moon = day - dom + 1; // New moon
386             offsetMonth(moon, dom, amount);
387         }
388         break;
389     default:
390         Calendar::add(field, amount, status);
391         break;
392     }
393 }
394 
395 /**
396  * Override Calendar to handle leap months properly.
397  * @stable ICU 2.8
398  */
add(EDateFields field,int32_t amount,UErrorCode & status)399 void ChineseCalendar::add(EDateFields field, int32_t amount, UErrorCode& status) {
400     add((UCalendarDateFields)field, amount, status);
401 }
402 
403 /**
404  * Override Calendar to handle leap months properly.
405  * @stable ICU 2.8
406  */
roll(UCalendarDateFields field,int32_t amount,UErrorCode & status)407 void ChineseCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) {
408     switch (field) {
409     case UCAL_MONTH:
410     case UCAL_ORDINAL_MONTH:
411         if (amount != 0) {
412             int32_t dom = get(UCAL_DAY_OF_MONTH, status);
413             if (U_FAILURE(status)) break;
414             int32_t day = get(UCAL_JULIAN_DAY, status) - kEpochStartAsJulianDay; // Get local day
415             if (U_FAILURE(status)) break;
416             int32_t moon = day - dom + 1; // New moon (start of this month)
417 
418             // Note throughout the following:  Months 12 and 1 are never
419             // followed by a leap month (D&R p. 185).
420 
421             // Compute the adjusted month number m.  This is zero-based
422             // value from 0..11 in a non-leap year, and from 0..12 in a
423             // leap year.
424             int32_t m = get(UCAL_MONTH, status); // 0-based month
425             if (U_FAILURE(status)) break;
426             if (hasLeapMonthBetweenWinterSolstices) { // (member variable)
427                 if (get(UCAL_IS_LEAP_MONTH, status) == 1) {
428                     ++m;
429                 } else {
430                     // Check for a prior leap month.  (In the
431                     // following, month 0 is the first month of the
432                     // year.)  Month 0 is never followed by a leap
433                     // month, and we know month m is not a leap month.
434                     // moon1 will be the start of month 0 if there is
435                     // no leap month between month 0 and month m;
436                     // otherwise it will be the start of month 1.
437                     int moon1 = moon -
438                         (int) (CalendarAstronomer::SYNODIC_MONTH * (m - 0.5));
439                     moon1 = newMoonNear(moon1, true);
440                     if (isLeapMonthBetween(moon1, moon)) {
441                         ++m;
442                     }
443                 }
444                 if (U_FAILURE(status)) break;
445             }
446 
447             // Now do the standard roll computation on m, with the
448             // allowed range of 0..n-1, where n is 12 or 13.
449             int32_t n = hasLeapMonthBetweenWinterSolstices ? 13 : 12; // Months in this year
450             int32_t newM = (m + amount) % n;
451             if (newM < 0) {
452                 newM += n;
453             }
454 
455             if (newM != m) {
456                 offsetMonth(moon, dom, newM - m);
457             }
458         }
459         break;
460     default:
461         Calendar::roll(field, amount, status);
462         break;
463     }
464 }
465 
roll(EDateFields field,int32_t amount,UErrorCode & status)466 void ChineseCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) {
467     roll((UCalendarDateFields)field, amount, status);
468 }
469 
470 
471 //------------------------------------------------------------------
472 // Support methods and constants
473 //------------------------------------------------------------------
474 
475 /**
476  * Convert local days to UTC epoch milliseconds.
477  * This is not an accurate conversion in that getTimezoneOffset
478  * takes the milliseconds in GMT (not local time). In theory, more
479  * accurate algorithm can be implemented but practically we do not need
480  * to go through that complication as long as the historical timezone
481  * changes did not happen around the 'tricky' new moon (new moon around
482  * midnight).
483  *
484  * @param days days after January 1, 1970 0:00 in the astronomical base zone
485  * @return milliseconds after January 1, 1970 0:00 GMT
486  */
daysToMillis(double days) const487 double ChineseCalendar::daysToMillis(double days) const {
488     double millis = days * (double)kOneDay;
489     if (fZoneAstroCalc != nullptr) {
490         int32_t rawOffset, dstOffset;
491         UErrorCode status = U_ZERO_ERROR;
492         fZoneAstroCalc->getOffset(millis, false, rawOffset, dstOffset, status);
493         if (U_SUCCESS(status)) {
494         	return millis - (double)(rawOffset + dstOffset);
495         }
496     }
497     return millis - (double)CHINA_OFFSET;
498 }
499 
500 /**
501  * Convert UTC epoch milliseconds to local days.
502  * @param millis milliseconds after January 1, 1970 0:00 GMT
503  * @return days after January 1, 1970 0:00 in the astronomical base zone
504  */
millisToDays(double millis) const505 double ChineseCalendar::millisToDays(double millis) const {
506     if (fZoneAstroCalc != nullptr) {
507         int32_t rawOffset, dstOffset;
508         UErrorCode status = U_ZERO_ERROR;
509         fZoneAstroCalc->getOffset(millis, false, rawOffset, dstOffset, status);
510         if (U_SUCCESS(status)) {
511         	return ClockMath::floorDivide(millis + (double)(rawOffset + dstOffset), kOneDay);
512         }
513     }
514     return ClockMath::floorDivide(millis + (double)CHINA_OFFSET, kOneDay);
515 }
516 
517 //------------------------------------------------------------------
518 // Astronomical computations
519 //------------------------------------------------------------------
520 
521 
522 /**
523  * Return the major solar term on or after December 15 of the given
524  * Gregorian year, that is, the winter solstice of the given year.
525  * Computations are relative to Asia/Shanghai time zone.
526  * @param gyear a Gregorian year
527  * @return days after January 1, 1970 0:00 Asia/Shanghai of the
528  * winter solstice of the given year
529  */
winterSolstice(int32_t gyear) const530 int32_t ChineseCalendar::winterSolstice(int32_t gyear) const {
531 
532     UErrorCode status = U_ZERO_ERROR;
533     int32_t cacheValue = CalendarCache::get(&gChineseCalendarWinterSolsticeCache, gyear, status);
534 
535     if (cacheValue == 0) {
536         // In books December 15 is used, but it fails for some years
537         // using our algorithms, e.g.: 1298 1391 1492 1553 1560.  That
538         // is, winterSolstice(1298) starts search at Dec 14 08:00:00
539         // PST 1298 with a final result of Dec 14 10:31:59 PST 1299.
540         double ms = daysToMillis(Grego::fieldsToDay(gyear, UCAL_DECEMBER, 1));
541 
542         umtx_lock(&astroLock);
543         if(gChineseCalendarAstro == nullptr) {
544             gChineseCalendarAstro = new CalendarAstronomer();
545             ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR, calendar_chinese_cleanup);
546         }
547         gChineseCalendarAstro->setTime(ms);
548         UDate solarLong = gChineseCalendarAstro->getSunTime(CalendarAstronomer::WINTER_SOLSTICE(), true);
549         umtx_unlock(&astroLock);
550 
551         // Winter solstice is 270 degrees solar longitude aka Dongzhi
552         cacheValue = (int32_t)millisToDays(solarLong);
553         CalendarCache::put(&gChineseCalendarWinterSolsticeCache, gyear, cacheValue, status);
554     }
555     if(U_FAILURE(status)) {
556         cacheValue = 0;
557     }
558     return cacheValue;
559 }
560 
561 /**
562  * Return the closest new moon to the given date, searching either
563  * forward or backward in time.
564  * @param days days after January 1, 1970 0:00 Asia/Shanghai
565  * @param after if true, search for a new moon on or after the given
566  * date; otherwise, search for a new moon before it
567  * @return days after January 1, 1970 0:00 Asia/Shanghai of the nearest
568  * new moon after or before <code>days</code>
569  */
newMoonNear(double days,UBool after) const570 int32_t ChineseCalendar::newMoonNear(double days, UBool after) const {
571 
572     umtx_lock(&astroLock);
573     if(gChineseCalendarAstro == nullptr) {
574         gChineseCalendarAstro = new CalendarAstronomer();
575         ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR, calendar_chinese_cleanup);
576     }
577     gChineseCalendarAstro->setTime(daysToMillis(days));
578     UDate newMoon = gChineseCalendarAstro->getMoonTime(CalendarAstronomer::NEW_MOON(), after);
579     umtx_unlock(&astroLock);
580 
581     return (int32_t) millisToDays(newMoon);
582 }
583 
584 /**
585  * Return the nearest integer number of synodic months between
586  * two dates.
587  * @param day1 days after January 1, 1970 0:00 Asia/Shanghai
588  * @param day2 days after January 1, 1970 0:00 Asia/Shanghai
589  * @return the nearest integer number of months between day1 and day2
590  */
synodicMonthsBetween(int32_t day1,int32_t day2) const591 int32_t ChineseCalendar::synodicMonthsBetween(int32_t day1, int32_t day2) const {
592     double roundme = ((day2 - day1) / CalendarAstronomer::SYNODIC_MONTH);
593     return (int32_t) (roundme + (roundme >= 0 ? .5 : -.5));
594 }
595 
596 /**
597  * Return the major solar term on or before a given date.  This
598  * will be an integer from 1..12, with 1 corresponding to 330 degrees,
599  * 2 to 0 degrees, 3 to 30 degrees,..., and 12 to 300 degrees.
600  * @param days days after January 1, 1970 0:00 Asia/Shanghai
601  */
majorSolarTerm(int32_t days) const602 int32_t ChineseCalendar::majorSolarTerm(int32_t days) const {
603 
604     umtx_lock(&astroLock);
605     if(gChineseCalendarAstro == nullptr) {
606         gChineseCalendarAstro = new CalendarAstronomer();
607         ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR, calendar_chinese_cleanup);
608     }
609     gChineseCalendarAstro->setTime(daysToMillis(days));
610     UDate solarLongitude = gChineseCalendarAstro->getSunLongitude();
611     umtx_unlock(&astroLock);
612 
613     // Compute (floor(solarLongitude / (pi/6)) + 2) % 12
614     int32_t term = ( ((int32_t)(6 * solarLongitude / CalendarAstronomer::PI)) + 2 ) % 12;
615     if (term < 1) {
616         term += 12;
617     }
618     return term;
619 }
620 
621 /**
622  * Return true if the given month lacks a major solar term.
623  * @param newMoon days after January 1, 1970 0:00 Asia/Shanghai of a new
624  * moon
625  */
hasNoMajorSolarTerm(int32_t newMoon) const626 UBool ChineseCalendar::hasNoMajorSolarTerm(int32_t newMoon) const {
627     return majorSolarTerm(newMoon) ==
628         majorSolarTerm(newMoonNear(newMoon + SYNODIC_GAP, true));
629 }
630 
631 
632 //------------------------------------------------------------------
633 // Time to fields
634 //------------------------------------------------------------------
635 
636 /**
637  * Return true if there is a leap month on or after month newMoon1 and
638  * at or before month newMoon2.
639  * @param newMoon1 days after January 1, 1970 0:00 astronomical base zone
640  * of a new moon
641  * @param newMoon2 days after January 1, 1970 0:00 astronomical base zone
642  * of a new moon
643  */
isLeapMonthBetween(int32_t newMoon1,int32_t newMoon2) const644 UBool ChineseCalendar::isLeapMonthBetween(int32_t newMoon1, int32_t newMoon2) const {
645 
646 #ifdef U_DEBUG_CHNSECAL
647     // This is only needed to debug the timeOfAngle divergence bug.
648     // Remove this later. Liu 11/9/00
649     if (synodicMonthsBetween(newMoon1, newMoon2) >= 50) {
650         U_DEBUG_CHNSECAL_MSG((
651             "isLeapMonthBetween(%d, %d): Invalid parameters", newMoon1, newMoon2
652             ));
653     }
654 #endif
655 
656     return (newMoon2 >= newMoon1) &&
657         (isLeapMonthBetween(newMoon1, newMoonNear(newMoon2 - SYNODIC_GAP, false)) ||
658          hasNoMajorSolarTerm(newMoon2));
659 }
660 
661 /**
662  * Compute fields for the Chinese calendar system.  This method can
663  * either set all relevant fields, as required by
664  * <code>handleComputeFields()</code>, or it can just set the MONTH and
665  * IS_LEAP_MONTH fields, as required by
666  * <code>handleComputeMonthStart()</code>.
667  *
668  * <p>As a side effect, this method sets {@link #hasLeapMonthBetweenWinterSolstices}.
669  * @param days days after January 1, 1970 0:00 astronomical base zone
670  * of the date to compute fields for
671  * @param gyear the Gregorian year of the given date
672  * @param gmonth the Gregorian month of the given date
673  * @param setAllFields if true, set the EXTENDED_YEAR, ERA, YEAR,
674  * DAY_OF_MONTH, and DAY_OF_YEAR fields.  In either case set the MONTH
675  * and IS_LEAP_MONTH fields.
676  */
computeChineseFields(int32_t days,int32_t gyear,int32_t gmonth,UBool setAllFields)677 void ChineseCalendar::computeChineseFields(int32_t days, int32_t gyear, int32_t gmonth,
678                                   UBool setAllFields) {
679     // Find the winter solstices before and after the target date.
680     // These define the boundaries of this Chinese year, specifically,
681     // the position of month 11, which always contains the solstice.
682     // We want solsticeBefore <= date < solsticeAfter.
683     int32_t solsticeBefore;
684     int32_t solsticeAfter = winterSolstice(gyear);
685     if (days < solsticeAfter) {
686         solsticeBefore = winterSolstice(gyear - 1);
687     } else {
688         solsticeBefore = solsticeAfter;
689         solsticeAfter = winterSolstice(gyear + 1);
690     }
691 
692     // Find the start of the month after month 11.  This will be either
693     // the prior month 12 or leap month 11 (very rare).  Also find the
694     // start of the following month 11.
695     int32_t firstMoon = newMoonNear(solsticeBefore + 1, true);
696     int32_t lastMoon = newMoonNear(solsticeAfter + 1, false);
697     int32_t thisMoon = newMoonNear(days + 1, false); // Start of this month
698     // Note: hasLeapMonthBetweenWinterSolstices is a member variable
699     hasLeapMonthBetweenWinterSolstices = synodicMonthsBetween(firstMoon, lastMoon) == 12;
700 
701     int32_t month = synodicMonthsBetween(firstMoon, thisMoon);
702     int32_t theNewYear = newYear(gyear);
703     if (days < theNewYear) {
704         theNewYear = newYear(gyear-1);
705     }
706     if (hasLeapMonthBetweenWinterSolstices && isLeapMonthBetween(firstMoon, thisMoon)) {
707         month--;
708     }
709     if (month < 1) {
710         month += 12;
711     }
712     int32_t ordinalMonth = synodicMonthsBetween(theNewYear, thisMoon);
713     if (ordinalMonth < 0) {
714         ordinalMonth += 12;
715     }
716     UBool isLeapMonth = hasLeapMonthBetweenWinterSolstices &&
717         hasNoMajorSolarTerm(thisMoon) &&
718         !isLeapMonthBetween(firstMoon, newMoonNear(thisMoon - SYNODIC_GAP, false));
719 
720     internalSet(UCAL_MONTH, month-1); // Convert from 1-based to 0-based
721     internalSet(UCAL_ORDINAL_MONTH, ordinalMonth); // Convert from 1-based to 0-based
722     internalSet(UCAL_IS_LEAP_MONTH, isLeapMonth?1:0);
723 
724 
725     if (setAllFields) {
726 
727         // Extended year and cycle year is based on the epoch year
728 
729         int32_t extended_year = gyear - fEpochYear;
730         int cycle_year = gyear - CHINESE_EPOCH_YEAR;
731         if (month < 11 ||
732             gmonth >= UCAL_JULY) {
733             extended_year++;
734             cycle_year++;
735         }
736         int32_t dayOfMonth = days - thisMoon + 1;
737 
738         internalSet(UCAL_EXTENDED_YEAR, extended_year);
739 
740         // 0->0,60  1->1,1  60->1,60  61->2,1  etc.
741         int32_t yearOfCycle;
742         int32_t cycle = ClockMath::floorDivide(cycle_year - 1, 60, &yearOfCycle);
743         internalSet(UCAL_ERA, cycle + 1);
744         internalSet(UCAL_YEAR, yearOfCycle + 1);
745 
746         internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);
747 
748         // Days will be before the first new year we compute if this
749         // date is in month 11, leap 11, 12.  There is never a leap 12.
750         // New year computations are cached so this should be cheap in
751         // the long run.
752         int32_t theNewYear = newYear(gyear);
753         if (days < theNewYear) {
754             theNewYear = newYear(gyear-1);
755         }
756         internalSet(UCAL_DAY_OF_YEAR, days - theNewYear + 1);
757     }
758 }
759 
760 
761 //------------------------------------------------------------------
762 // Fields to time
763 //------------------------------------------------------------------
764 
765 /**
766  * Return the Chinese new year of the given Gregorian year.
767  * @param gyear a Gregorian year
768  * @return days after January 1, 1970 0:00 astronomical base zone of the
769  * Chinese new year of the given year (this will be a new moon)
770  */
newYear(int32_t gyear) const771 int32_t ChineseCalendar::newYear(int32_t gyear) const {
772     UErrorCode status = U_ZERO_ERROR;
773     int32_t cacheValue = CalendarCache::get(&gChineseCalendarNewYearCache, gyear, status);
774 
775     if (cacheValue == 0) {
776 
777         int32_t solsticeBefore= winterSolstice(gyear - 1);
778         int32_t solsticeAfter = winterSolstice(gyear);
779         int32_t newMoon1 = newMoonNear(solsticeBefore + 1, true);
780         int32_t newMoon2 = newMoonNear(newMoon1 + SYNODIC_GAP, true);
781         int32_t newMoon11 = newMoonNear(solsticeAfter + 1, false);
782 
783         if (synodicMonthsBetween(newMoon1, newMoon11) == 12 &&
784             (hasNoMajorSolarTerm(newMoon1) || hasNoMajorSolarTerm(newMoon2))) {
785             cacheValue = newMoonNear(newMoon2 + SYNODIC_GAP, true);
786         } else {
787             cacheValue = newMoon2;
788         }
789 
790         CalendarCache::put(&gChineseCalendarNewYearCache, gyear, cacheValue, status);
791     }
792     if(U_FAILURE(status)) {
793         cacheValue = 0;
794     }
795     return cacheValue;
796 }
797 
798 /**
799  * Adjust this calendar to be delta months before or after a given
800  * start position, pinning the day of month if necessary.  The start
801  * position is given as a local days number for the start of the month
802  * and a day-of-month.  Used by add() and roll().
803  * @param newMoon the local days of the first day of the month of the
804  * start position (days after January 1, 1970 0:00 Asia/Shanghai)
805  * @param dom the 1-based day-of-month of the start position
806  * @param delta the number of months to move forward or backward from
807  * the start position
808  */
offsetMonth(int32_t newMoon,int32_t dom,int32_t delta)809 void ChineseCalendar::offsetMonth(int32_t newMoon, int32_t dom, int32_t delta) {
810     UErrorCode status = U_ZERO_ERROR;
811 
812     // Move to the middle of the month before our target month.
813     newMoon += (int32_t) (CalendarAstronomer::SYNODIC_MONTH * (delta - 0.5));
814 
815     // Search forward to the target month's new moon
816     newMoon = newMoonNear(newMoon, true);
817 
818     // Find the target dom
819     int32_t jd = newMoon + kEpochStartAsJulianDay - 1 + dom;
820 
821     // Pin the dom.  In this calendar all months are 29 or 30 days
822     // so pinning just means handling dom 30.
823     if (dom > 29) {
824         set(UCAL_JULIAN_DAY, jd-1);
825         // TODO Fix this.  We really shouldn't ever have to
826         // explicitly call complete().  This is either a bug in
827         // this method, in ChineseCalendar, or in
828         // Calendar.getActualMaximum().  I suspect the last.
829         complete(status);
830         if (U_FAILURE(status)) return;
831         if (getActualMaximum(UCAL_DAY_OF_MONTH, status) >= dom) {
832             if (U_FAILURE(status)) return;
833             set(UCAL_JULIAN_DAY, jd);
834         }
835     } else {
836         set(UCAL_JULIAN_DAY, jd);
837     }
838 }
839 
840 constexpr uint32_t kChineseRelatedYearDiff = -2637;
841 
getRelatedYear(UErrorCode & status) const842 int32_t ChineseCalendar::getRelatedYear(UErrorCode &status) const
843 {
844     int32_t year = get(UCAL_EXTENDED_YEAR, status);
845     if (U_FAILURE(status)) {
846         return 0;
847     }
848     return year + kChineseRelatedYearDiff;
849 }
850 
setRelatedYear(int32_t year)851 void ChineseCalendar::setRelatedYear(int32_t year)
852 {
853     // set extended year
854     set(UCAL_EXTENDED_YEAR, year - kChineseRelatedYearDiff);
855 }
856 
857 // default century
858 
859 static UDate     gSystemDefaultCenturyStart       = DBL_MIN;
860 static int32_t   gSystemDefaultCenturyStartYear   = -1;
861 static icu::UInitOnce gSystemDefaultCenturyInitOnce {};
862 
863 
haveDefaultCentury() const864 UBool ChineseCalendar::haveDefaultCentury() const
865 {
866     return true;
867 }
868 
defaultCenturyStart() const869 UDate ChineseCalendar::defaultCenturyStart() const
870 {
871     return internalGetDefaultCenturyStart();
872 }
873 
defaultCenturyStartYear() const874 int32_t ChineseCalendar::defaultCenturyStartYear() const
875 {
876     return internalGetDefaultCenturyStartYear();
877 }
878 
initializeSystemDefaultCentury()879 static void U_CALLCONV initializeSystemDefaultCentury()
880 {
881     // initialize systemDefaultCentury and systemDefaultCenturyYear based
882     // on the current time.  They'll be set to 80 years before
883     // the current time.
884     UErrorCode status = U_ZERO_ERROR;
885     ChineseCalendar calendar(Locale("@calendar=chinese"),status);
886     if (U_SUCCESS(status)) {
887         calendar.setTime(Calendar::getNow(), status);
888         calendar.add(UCAL_YEAR, -80, status);
889         gSystemDefaultCenturyStart     = calendar.getTime(status);
890         gSystemDefaultCenturyStartYear = calendar.get(UCAL_YEAR, status);
891     }
892     // We have no recourse upon failure unless we want to propagate the failure
893     // out.
894 }
895 
896 UDate
internalGetDefaultCenturyStart() const897 ChineseCalendar::internalGetDefaultCenturyStart() const
898 {
899     // lazy-evaluate systemDefaultCenturyStart
900     umtx_initOnce(gSystemDefaultCenturyInitOnce, &initializeSystemDefaultCentury);
901     return gSystemDefaultCenturyStart;
902 }
903 
904 int32_t
internalGetDefaultCenturyStartYear() const905 ChineseCalendar::internalGetDefaultCenturyStartYear() const
906 {
907     // lazy-evaluate systemDefaultCenturyStartYear
908     umtx_initOnce(gSystemDefaultCenturyInitOnce, &initializeSystemDefaultCentury);
909     return    gSystemDefaultCenturyStartYear;
910 }
911 
912 bool
inTemporalLeapYear(UErrorCode & status) const913 ChineseCalendar::inTemporalLeapYear(UErrorCode &status) const
914 {
915     int32_t days = getActualMaximum(UCAL_DAY_OF_YEAR, status);
916     if (U_FAILURE(status)) return false;
917     return days > 360;
918 }
919 
920 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(ChineseCalendar)
921 
922 
923 static const char * const gTemporalLeapMonthCodes[] = {
924     "M01L", "M02L", "M03L", "M04L", "M05L", "M06L",
925     "M07L", "M08L", "M09L", "M10L", "M11L", "M12L", nullptr
926 };
927 
getTemporalMonthCode(UErrorCode & status) const928 const char* ChineseCalendar::getTemporalMonthCode(UErrorCode &status) const {
929     // We need to call get, not internalGet, to force the calculation
930     // from UCAL_ORDINAL_MONTH.
931     int32_t is_leap = get(UCAL_IS_LEAP_MONTH, status);
932     if (U_FAILURE(status)) return nullptr;
933     if (is_leap != 0) {
934         int32_t month = get(UCAL_MONTH, status);
935         if (U_FAILURE(status)) return nullptr;
936         return gTemporalLeapMonthCodes[month];
937     }
938     return Calendar::getTemporalMonthCode(status);
939 }
940 
941 void
setTemporalMonthCode(const char * code,UErrorCode & status)942 ChineseCalendar::setTemporalMonthCode(const char* code, UErrorCode& status )
943 {
944     if (U_FAILURE(status)) return;
945     int32_t len = static_cast<int32_t>(uprv_strlen(code));
946     if (len != 4 || code[0] != 'M' || code[3] != 'L') {
947         set(UCAL_IS_LEAP_MONTH, 0);
948         return Calendar::setTemporalMonthCode(code, status);
949     }
950     for (int m = 0; gTemporalLeapMonthCodes[m] != nullptr; m++) {
951         if (uprv_strcmp(code, gTemporalLeapMonthCodes[m]) == 0) {
952             set(UCAL_MONTH, m);
953             set(UCAL_IS_LEAP_MONTH, 1);
954             return;
955         }
956     }
957     status = U_ILLEGAL_ARGUMENT_ERROR;
958 }
959 
internalGetMonth() const960 int32_t ChineseCalendar::internalGetMonth() const {
961     if (resolveFields(kMonthPrecedence) == UCAL_MONTH) {
962         return internalGet(UCAL_MONTH);
963     }
964     LocalPointer<Calendar> temp(this->clone());
965     temp->set(UCAL_MONTH, 0);
966     temp->set(UCAL_IS_LEAP_MONTH, 0);
967     temp->set(UCAL_DATE, 1);
968     // Calculate the UCAL_MONTH and UCAL_IS_LEAP_MONTH by adding number of
969     // months.
970     UErrorCode status = U_ZERO_ERROR;
971     temp->roll(UCAL_MONTH, internalGet(UCAL_ORDINAL_MONTH), status);
972 
973 
974     ChineseCalendar *nonConstThis = (ChineseCalendar*)this; // cast away const
975     nonConstThis->internalSet(UCAL_IS_LEAP_MONTH, temp->get(UCAL_IS_LEAP_MONTH, status));
976     int32_t month = temp->get(UCAL_MONTH, status);
977     U_ASSERT(U_SUCCESS(status));
978     nonConstThis->internalSet(UCAL_MONTH, month);
979     return month;
980 }
981 
internalGetMonth(int32_t defaultValue) const982 int32_t ChineseCalendar::internalGetMonth(int32_t defaultValue) const {
983     if (resolveFields(kMonthPrecedence) == UCAL_MONTH) {
984         return internalGet(UCAL_MONTH, defaultValue);
985     }
986     return internalGetMonth();
987 }
988 
989 U_NAMESPACE_END
990 
991 #endif
992 
993