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