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