1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 ******************************************************************************
5 * Copyright (C) 2007-2014, International Business Machines Corporation
6 * and others. All Rights Reserved.
7 ******************************************************************************
11 * Modification History:
13 * Date Name Description
14 * 9/18/2007 ajmacher ported from java ChineseCalendar
15 *****************************************************************************
20 #if !UCONFIG_NO_FORMATTING
24 #include "gregoimp.h" // Math
25 #include "astro.h" // CalendarAstronomer
26 #include "unicode/simpletz.h"
31 #ifdef U_DEBUG_CHNSECAL
34 static void debug_chnsecal_loc(const char *f
, int32_t l
)
36 fprintf(stderr
, "%s:%d: ", f
, l
);
39 static void debug_chnsecal_msg(const char *pat
, ...)
43 vfprintf(stderr
, pat
, ap
);
46 // must use double parens, i.e.: U_DEBUG_CHNSECAL_MSG(("four is: %d",4));
47 #define U_DEBUG_CHNSECAL_MSG(x) {debug_chnsecal_loc(__FILE__,__LINE__);debug_chnsecal_msg x;}
49 #define U_DEBUG_CHNSECAL_MSG(x)
54 static UMutex astroLock
= U_MUTEX_INITIALIZER
; // Protects access to gChineseCalendarAstro.
55 static icu::CalendarAstronomer
*gChineseCalendarAstro
= NULL
;
57 // Lazy Creation & Access synchronized by class CalendarCache with a mutex.
58 static icu::CalendarCache
*gChineseCalendarWinterSolsticeCache
= NULL
;
59 static icu::CalendarCache
*gChineseCalendarNewYearCache
= NULL
;
61 static icu::TimeZone
*gChineseCalendarZoneAstroCalc
= NULL
;
62 static icu::UInitOnce gChineseCalendarZoneAstroCalcInitOnce
= U_INITONCE_INITIALIZER
;
65 * The start year of the Chinese calendar, the 61st year of the reign
66 * of Huang Di. Some sources use the first year of his reign,
67 * resulting in EXTENDED_YEAR values 60 years greater and ERA (cycle)
70 static const int32_t CHINESE_EPOCH_YEAR
= -2636; // Gregorian year
73 * The offset from GMT in milliseconds at which we perform astronomical
74 * computations. Some sources use a different historically accurate
75 * offset of GMT+7:45:40 for years before 1929; we do not do this.
77 static const int32_t CHINA_OFFSET
= 8 * kOneHour
;
80 * Value to be added or subtracted from the local days of a new moon to
81 * get close to the next or prior new moon, but not cross it. Must be
82 * >= 1 and < CalendarAstronomer.SYNODIC_MONTH.
84 static const int32_t SYNODIC_GAP
= 25;
88 static UBool
calendar_chinese_cleanup(void) {
89 if (gChineseCalendarAstro
) {
90 delete gChineseCalendarAstro
;
91 gChineseCalendarAstro
= NULL
;
93 if (gChineseCalendarWinterSolsticeCache
) {
94 delete gChineseCalendarWinterSolsticeCache
;
95 gChineseCalendarWinterSolsticeCache
= NULL
;
97 if (gChineseCalendarNewYearCache
) {
98 delete gChineseCalendarNewYearCache
;
99 gChineseCalendarNewYearCache
= NULL
;
101 if (gChineseCalendarZoneAstroCalc
) {
102 delete gChineseCalendarZoneAstroCalc
;
103 gChineseCalendarZoneAstroCalc
= NULL
;
105 gChineseCalendarZoneAstroCalcInitOnce
.reset();
113 // Implementation of the ChineseCalendar class
116 //-------------------------------------------------------------------------
118 //-------------------------------------------------------------------------
121 Calendar
* ChineseCalendar::clone() const {
122 return new ChineseCalendar(*this);
125 ChineseCalendar::ChineseCalendar(const Locale
& aLocale
, UErrorCode
& success
)
126 : Calendar(TimeZone::createDefault(), aLocale
, success
),
128 fEpochYear(CHINESE_EPOCH_YEAR
),
129 fZoneAstroCalc(getChineseCalZoneAstroCalc())
131 setTimeInMillis(getNow(), success
); // Call this again now that the vtable is set up properly.
134 ChineseCalendar::ChineseCalendar(const Locale
& aLocale
, int32_t epochYear
,
135 const TimeZone
* zoneAstroCalc
, UErrorCode
&success
)
136 : Calendar(TimeZone::createDefault(), aLocale
, success
),
138 fEpochYear(epochYear
),
139 fZoneAstroCalc(zoneAstroCalc
)
141 setTimeInMillis(getNow(), success
); // Call this again now that the vtable is set up properly.
144 ChineseCalendar::ChineseCalendar(const ChineseCalendar
& other
) : Calendar(other
) {
145 isLeapYear
= other
.isLeapYear
;
146 fEpochYear
= other
.fEpochYear
;
147 fZoneAstroCalc
= other
.fZoneAstroCalc
;
150 ChineseCalendar::~ChineseCalendar()
154 const char *ChineseCalendar::getType() const {
158 static void U_CALLCONV
initChineseCalZoneAstroCalc() {
159 gChineseCalendarZoneAstroCalc
= new SimpleTimeZone(CHINA_OFFSET
, UNICODE_STRING_SIMPLE("CHINA_ZONE") );
160 ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR
, calendar_chinese_cleanup
);
163 const TimeZone
* ChineseCalendar::getChineseCalZoneAstroCalc(void) const {
164 umtx_initOnce(gChineseCalendarZoneAstroCalcInitOnce
, &initChineseCalZoneAstroCalc
);
165 return gChineseCalendarZoneAstroCalc
;
168 //-------------------------------------------------------------------------
169 // Minimum / Maximum access functions
170 //-------------------------------------------------------------------------
173 static const int32_t LIMITS
[UCAL_FIELD_COUNT
][4] = {
174 // Minimum Greatest Least Maximum
176 { 1, 1, 83333, 83333}, // ERA
177 { 1, 1, 60, 60}, // YEAR
178 { 0, 0, 11, 11}, // MONTH
179 { 1, 1, 50, 55}, // WEEK_OF_YEAR
180 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // WEEK_OF_MONTH
181 { 1, 1, 29, 30}, // DAY_OF_MONTH
182 { 1, 1, 353, 385}, // DAY_OF_YEAR
183 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK
184 { -1, -1, 5, 5}, // DAY_OF_WEEK_IN_MONTH
185 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM
186 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR
187 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY
188 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE
189 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND
190 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND
191 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET
192 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET
193 { -5000000, -5000000, 5000000, 5000000}, // YEAR_WOY
194 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL
195 { -5000000, -5000000, 5000000, 5000000}, // EXTENDED_YEAR
196 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY
197 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECONDS_IN_DAY
198 { 0, 0, 1, 1}, // IS_LEAP_MONTH
205 int32_t ChineseCalendar::handleGetLimit(UCalendarDateFields field
, ELimitType limitType
) const {
206 return LIMITS
[field
][limitType
];
210 //----------------------------------------------------------------------
211 // Calendar framework
212 //----------------------------------------------------------------------
215 * Implement abstract Calendar method to return the extended year
216 * defined by the current fields. This will use either the ERA and
217 * YEAR field as the cycle and year-of-cycle, or the EXTENDED_YEAR
218 * field as the continuous year count, depending on which is newer.
221 int32_t ChineseCalendar::handleGetExtendedYear() {
223 if (newestStamp(UCAL_ERA
, UCAL_YEAR
, kUnset
) <= fStamp
[UCAL_EXTENDED_YEAR
]) {
224 year
= internalGet(UCAL_EXTENDED_YEAR
, 1); // Default to year 1
226 int32_t cycle
= internalGet(UCAL_ERA
, 1) - 1; // 0-based cycle
227 // adjust to the instance specific epoch
228 year
= cycle
* 60 + internalGet(UCAL_YEAR
, 1) - (fEpochYear
- CHINESE_EPOCH_YEAR
);
234 * Override Calendar method to return the number of days in the given
235 * extended year and month.
237 * <p>Note: This method also reads the IS_LEAP_MONTH field to determine
238 * whether or not the given month is a leap month.
241 int32_t ChineseCalendar::handleGetMonthLength(int32_t extendedYear
, int32_t month
) const {
242 int32_t thisStart
= handleComputeMonthStart(extendedYear
, month
, TRUE
) -
243 kEpochStartAsJulianDay
+ 1; // Julian day -> local days
244 int32_t nextStart
= newMoonNear(thisStart
+ SYNODIC_GAP
, TRUE
);
245 return nextStart
- thisStart
;
249 * Override Calendar to compute several fields specific to the Chinese
250 * calendar system. These are:
257 * <li>EXTENDED_YEAR</ul>
259 * The DAY_OF_WEEK and DOW_LOCAL fields are already set when this
260 * method is called. The getGregorianXxx() methods return Gregorian
261 * calendar equivalents for the given Julian day.
263 * <p>Compute the ChineseCalendar-specific field IS_LEAP_MONTH.
266 void ChineseCalendar::handleComputeFields(int32_t julianDay
, UErrorCode
&/*status*/) {
268 computeChineseFields(julianDay
- kEpochStartAsJulianDay
, // local days
269 getGregorianYear(), getGregorianMonth(),
270 TRUE
); // set all fields
274 * Field resolution table that incorporates IS_LEAP_MONTH.
276 const UFieldResolutionTable
ChineseCalendar::CHINESE_DATE_PRECEDENCE
[] =
279 { UCAL_DAY_OF_MONTH
, kResolveSTOP
},
280 { UCAL_WEEK_OF_YEAR
, UCAL_DAY_OF_WEEK
, kResolveSTOP
},
281 { UCAL_WEEK_OF_MONTH
, UCAL_DAY_OF_WEEK
, kResolveSTOP
},
282 { UCAL_DAY_OF_WEEK_IN_MONTH
, UCAL_DAY_OF_WEEK
, kResolveSTOP
},
283 { UCAL_WEEK_OF_YEAR
, UCAL_DOW_LOCAL
, kResolveSTOP
},
284 { UCAL_WEEK_OF_MONTH
, UCAL_DOW_LOCAL
, kResolveSTOP
},
285 { UCAL_DAY_OF_WEEK_IN_MONTH
, UCAL_DOW_LOCAL
, kResolveSTOP
},
286 { UCAL_DAY_OF_YEAR
, kResolveSTOP
},
287 { kResolveRemap
| UCAL_DAY_OF_MONTH
, UCAL_IS_LEAP_MONTH
, kResolveSTOP
},
291 { UCAL_WEEK_OF_YEAR
, kResolveSTOP
},
292 { UCAL_WEEK_OF_MONTH
, kResolveSTOP
},
293 { UCAL_DAY_OF_WEEK_IN_MONTH
, kResolveSTOP
},
294 { kResolveRemap
| UCAL_DAY_OF_WEEK_IN_MONTH
, UCAL_DAY_OF_WEEK
, kResolveSTOP
},
295 { kResolveRemap
| UCAL_DAY_OF_WEEK_IN_MONTH
, UCAL_DOW_LOCAL
, kResolveSTOP
},
302 * Override Calendar to add IS_LEAP_MONTH to the field resolution
306 const UFieldResolutionTable
* ChineseCalendar::getFieldResolutionTable() const {
307 return CHINESE_DATE_PRECEDENCE
;
311 * Return the Julian day number of day before the first day of the
312 * given month in the given extended year.
314 * <p>Note: This method reads the IS_LEAP_MONTH field to determine
315 * whether the given month is a leap month.
316 * @param eyear the extended year
317 * @param month the zero-based month. The month is also determined
318 * by reading the IS_LEAP_MONTH field.
319 * @return the Julian day number of the day before the first
320 * day of the given month and year
323 int32_t ChineseCalendar::handleComputeMonthStart(int32_t eyear
, int32_t month
, UBool useMonth
) const {
325 ChineseCalendar
*nonConstThis
= (ChineseCalendar
*)this; // cast away const
327 // If the month is out of range, adjust it into range, and
328 // modify the extended year value accordingly.
329 if (month
< 0 || month
> 11) {
331 eyear
+= (int32_t)ClockMath::floorDivide(m
, 12.0, m
);
335 int32_t gyear
= eyear
+ fEpochYear
- 1; // Gregorian year
336 int32_t theNewYear
= newYear(gyear
);
337 int32_t newMoon
= newMoonNear(theNewYear
+ month
* 29, TRUE
);
339 int32_t julianDay
= newMoon
+ kEpochStartAsJulianDay
;
341 // Save fields for later restoration
342 int32_t saveMonth
= internalGet(UCAL_MONTH
);
343 int32_t saveIsLeapMonth
= internalGet(UCAL_IS_LEAP_MONTH
);
345 // Ignore IS_LEAP_MONTH field if useMonth is false
346 int32_t isLeapMonth
= useMonth
? saveIsLeapMonth
: 0;
348 UErrorCode status
= U_ZERO_ERROR
;
349 nonConstThis
->computeGregorianFields(julianDay
, status
);
350 if (U_FAILURE(status
))
353 // This will modify the MONTH and IS_LEAP_MONTH fields (only)
354 nonConstThis
->computeChineseFields(newMoon
, getGregorianYear(),
355 getGregorianMonth(), FALSE
);
357 if (month
!= internalGet(UCAL_MONTH
) ||
358 isLeapMonth
!= internalGet(UCAL_IS_LEAP_MONTH
)) {
359 newMoon
= newMoonNear(newMoon
+ SYNODIC_GAP
, TRUE
);
360 julianDay
= newMoon
+ kEpochStartAsJulianDay
;
363 nonConstThis
->internalSet(UCAL_MONTH
, saveMonth
);
364 nonConstThis
->internalSet(UCAL_IS_LEAP_MONTH
, saveIsLeapMonth
);
366 return julianDay
- 1;
371 * Override Calendar to handle leap months properly.
374 void ChineseCalendar::add(UCalendarDateFields field
, int32_t amount
, UErrorCode
& status
) {
378 int32_t dom
= get(UCAL_DAY_OF_MONTH
, status
);
379 if (U_FAILURE(status
)) break;
380 int32_t day
= get(UCAL_JULIAN_DAY
, status
) - kEpochStartAsJulianDay
; // Get local day
381 if (U_FAILURE(status
)) break;
382 int32_t moon
= day
- dom
+ 1; // New moon
383 offsetMonth(moon
, dom
, amount
);
387 Calendar::add(field
, amount
, status
);
393 * Override Calendar to handle leap months properly.
396 void ChineseCalendar::add(EDateFields field
, int32_t amount
, UErrorCode
& status
) {
397 add((UCalendarDateFields
)field
, amount
, status
);
401 * Override Calendar to handle leap months properly.
404 void ChineseCalendar::roll(UCalendarDateFields field
, int32_t amount
, UErrorCode
& status
) {
408 int32_t dom
= get(UCAL_DAY_OF_MONTH
, status
);
409 if (U_FAILURE(status
)) break;
410 int32_t day
= get(UCAL_JULIAN_DAY
, status
) - kEpochStartAsJulianDay
; // Get local day
411 if (U_FAILURE(status
)) break;
412 int32_t moon
= day
- dom
+ 1; // New moon (start of this month)
414 // Note throughout the following: Months 12 and 1 are never
415 // followed by a leap month (D&R p. 185).
417 // Compute the adjusted month number m. This is zero-based
418 // value from 0..11 in a non-leap year, and from 0..12 in a
420 int32_t m
= get(UCAL_MONTH
, status
); // 0-based month
421 if (U_FAILURE(status
)) break;
422 if (isLeapYear
) { // (member variable)
423 if (get(UCAL_IS_LEAP_MONTH
, status
) == 1) {
426 // Check for a prior leap month. (In the
427 // following, month 0 is the first month of the
428 // year.) Month 0 is never followed by a leap
429 // month, and we know month m is not a leap month.
430 // moon1 will be the start of month 0 if there is
431 // no leap month between month 0 and month m;
432 // otherwise it will be the start of month 1.
434 (int) (CalendarAstronomer::SYNODIC_MONTH
* (m
- 0.5));
435 moon1
= newMoonNear(moon1
, TRUE
);
436 if (isLeapMonthBetween(moon1
, moon
)) {
440 if (U_FAILURE(status
)) break;
443 // Now do the standard roll computation on m, with the
444 // allowed range of 0..n-1, where n is 12 or 13.
445 int32_t n
= isLeapYear
? 13 : 12; // Months in this year
446 int32_t newM
= (m
+ amount
) % n
;
452 offsetMonth(moon
, dom
, newM
- m
);
457 Calendar::roll(field
, amount
, status
);
462 void ChineseCalendar::roll(EDateFields field
, int32_t amount
, UErrorCode
& status
) {
463 roll((UCalendarDateFields
)field
, amount
, status
);
467 //------------------------------------------------------------------
468 // Support methods and constants
469 //------------------------------------------------------------------
472 * Convert local days to UTC epoch milliseconds.
473 * This is not an accurate conversion in that getTimezoneOffset
474 * takes the milliseconds in GMT (not local time). In theory, more
475 * accurate algorithm can be implemented but practically we do not need
476 * to go through that complication as long as the historical timezone
477 * changes did not happen around the 'tricky' new moon (new moon around
480 * @param days days after January 1, 1970 0:00 in the astronomical base zone
481 * @return milliseconds after January 1, 1970 0:00 GMT
483 double ChineseCalendar::daysToMillis(double days
) const {
484 double millis
= days
* (double)kOneDay
;
485 if (fZoneAstroCalc
!= NULL
) {
486 int32_t rawOffset
, dstOffset
;
487 UErrorCode status
= U_ZERO_ERROR
;
488 fZoneAstroCalc
->getOffset(millis
, FALSE
, rawOffset
, dstOffset
, status
);
489 if (U_SUCCESS(status
)) {
490 return millis
- (double)(rawOffset
+ dstOffset
);
493 return millis
- (double)CHINA_OFFSET
;
497 * Convert UTC epoch milliseconds to local days.
498 * @param millis milliseconds after January 1, 1970 0:00 GMT
499 * @return days after January 1, 1970 0:00 in the astronomical base zone
501 double ChineseCalendar::millisToDays(double millis
) const {
502 if (fZoneAstroCalc
!= NULL
) {
503 int32_t rawOffset
, dstOffset
;
504 UErrorCode status
= U_ZERO_ERROR
;
505 fZoneAstroCalc
->getOffset(millis
, FALSE
, rawOffset
, dstOffset
, status
);
506 if (U_SUCCESS(status
)) {
507 return ClockMath::floorDivide(millis
+ (double)(rawOffset
+ dstOffset
), kOneDay
);
510 return ClockMath::floorDivide(millis
+ (double)CHINA_OFFSET
, kOneDay
);
513 //------------------------------------------------------------------
514 // Astronomical computations
515 //------------------------------------------------------------------
517 // bit array for gregorian 1900-2100 indicating years in
518 // which the linear estimate needs to be adjusted by -1
519 static const uint16_t winterSolsticeAdj
[] = {
520 0x0001, // 1900-1915, deltas for 1900
521 0x0444, // 1916-1931, deltas for 1918, 1922, 1926
523 0x8880, // 1948-1963, deltas for 1955, 1959, 1963
525 0x1100, // 1980-1995, deltas for 1988, 1992
526 0x0011, // 1996-2011, deltas for 1996, 2000
527 0x2200, // 2012-2027, deltas for 2021, 2025
528 0x0022, // 2028-2043, deltas for 2029, 2033
529 0x4000, // 2044-2059, deltas for 2058
530 0x0444, // 2060-2075, deltas for 2062, 2066, 2070
531 0x8000, // 2076-2091, deltas for 2091
532 0x0088, // 2092-2100, deltas for 2095, 2099
536 * Return the major solar term on or after December 15 of the given
537 * Gregorian year, that is, the winter solstice of the given year.
538 * Computations are relative to Asia/Shanghai time zone.
539 * @param gyear a Gregorian year
540 * @return days after January 1, 1970 0:00 Asia/Shanghai of the
541 * winter solstice of the given year
543 int32_t ChineseCalendar::winterSolstice(int32_t gyear
) const {
544 if (gyear
>= 1900 && gyear
<= 2100) {
545 // Don't use cache, just return linear estimate + table correction
546 int32_t gyearadj
= gyear
- 1900;
547 int32_t result
= (int32_t)(365.243*((double)gyearadj
) - 0.3) - 25211;
548 uint16_t bitmap
= winterSolsticeAdj
[gyearadj
/ 16];
550 uint16_t bitmask
= 1 << (gyearadj
% 16);
551 if ((bitmask
& bitmap
) != 0) {
558 UErrorCode status
= U_ZERO_ERROR
;
559 int32_t cacheValue
= CalendarCache::get(&gChineseCalendarWinterSolsticeCache
, gyear
, status
);
561 if (cacheValue
== 0) {
562 // In books December 15 is used, but it fails for some years
563 // using our algorithms, e.g.: 1298 1391 1492 1553 1560. That
564 // is, winterSolstice(1298) starts search at Dec 14 08:00:00
565 // PST 1298 with a final result of Dec 14 10:31:59 PST 1299.
566 double ms
= daysToMillis(Grego::fieldsToDay(gyear
, UCAL_DECEMBER
, 1));
568 umtx_lock(&astroLock
);
569 if(gChineseCalendarAstro
== NULL
) {
570 gChineseCalendarAstro
= new CalendarAstronomer();
571 ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR
, calendar_chinese_cleanup
);
573 gChineseCalendarAstro
->setTime(ms
);
574 UDate solarLong
= gChineseCalendarAstro
->getSunTime(CalendarAstronomer::WINTER_SOLSTICE(), TRUE
);
575 umtx_unlock(&astroLock
);
577 // Winter solstice is 270 degrees solar longitude aka Dongzhi
578 cacheValue
= (int32_t)millisToDays(solarLong
);
579 CalendarCache::put(&gChineseCalendarWinterSolsticeCache
, gyear
, cacheValue
, status
);
581 if(U_FAILURE(status
)) {
588 * Return the closest new moon to the given date, searching either
589 * forward or backward in time.
590 * @param days days after January 1, 1970 0:00 Asia/Shanghai
591 * @param after if true, search for a new moon on or after the given
592 * date; otherwise, search for a new moon before it
593 * @return days after January 1, 1970 0:00 Asia/Shanghai of the nearest
594 * new moon after or before <code>days</code>
596 int32_t ChineseCalendar::newMoonNear(double days
, UBool after
) const {
597 double ms
= daysToMillis(days
);
598 // Try to get the new moon via static function directly from the table in
599 // CalendarAstronomer (for approx gregorian range 1900-2100) without having
600 // to use a CalendarAstronomer instance which requires a lock. This still
601 // involves extra conversion to/from millis. If static function returns 0
602 // we are out of its range and need to use the full machinery.
603 UDate newMoon
= CalendarAstronomer::getNewMoonTimeInRange(ms
, after
);
604 if (newMoon
== 0.0) {
605 umtx_lock(&astroLock
);
606 if(gChineseCalendarAstro
== NULL
) {
607 gChineseCalendarAstro
= new CalendarAstronomer();
608 ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR
, calendar_chinese_cleanup
);
610 gChineseCalendarAstro
->setTime(ms
);
611 newMoon
= gChineseCalendarAstro
->getMoonTime(CalendarAstronomer::NEW_MOON(), after
);
612 umtx_unlock(&astroLock
);
615 return (int32_t) millisToDays(newMoon
);
619 * Return the nearest integer number of synodic months between
621 * @param day1 days after January 1, 1970 0:00 Asia/Shanghai
622 * @param day2 days after January 1, 1970 0:00 Asia/Shanghai
623 * @return the nearest integer number of months between day1 and day2
625 int32_t ChineseCalendar::synodicMonthsBetween(int32_t day1
, int32_t day2
) const {
626 double roundme
= ((day2
- day1
) / CalendarAstronomer::SYNODIC_MONTH
);
627 return (int32_t) (roundme
+ (roundme
>= 0 ? .5 : -.5));
631 * Return the major solar term on or before a given date. This
632 * will be an integer from 1..12, with 1 corresponding to 330 degrees,
633 * 2 to 0 degrees, 3 to 30 degrees,..., and 12 to 300 degrees.
634 * @param days days after January 1, 1970 0:00 Asia/Shanghai
636 int32_t ChineseCalendar::majorSolarTerm(int32_t days
) const {
638 double ms
= daysToMillis(days
);
639 UDate solarLongitude
= CalendarAstronomer::getSunLongitudeForTime(ms
);
641 // There was almost never any benefit to using the CalendarAstronomer instance;
642 // it could cache intermediate results, but we rarely used it multiple times in
643 // succession for the same setTime value, so the intermediate results got
646 // Deleted call to gChineseCalendarAstro->getSunLongitude() now that
647 // we use CalendarAstronomer::getSunLongitudeForTime()
649 // Compute (floor(solarLongitude / (pi/6)) + 2) % 12
650 int32_t term
= ( ((int32_t)(6 * solarLongitude
/ CalendarAstronomer::PI
)) + 2 ) % 12;
658 * Return true if the given month lacks a major solar term.
659 * @param newMoon days after January 1, 1970 0:00 Asia/Shanghai of a new
662 UBool
ChineseCalendar::hasNoMajorSolarTerm(int32_t newMoon
) const {
663 return majorSolarTerm(newMoon
) ==
664 majorSolarTerm(newMoonNear(newMoon
+ SYNODIC_GAP
, TRUE
));
668 //------------------------------------------------------------------
670 //------------------------------------------------------------------
673 * Return true if there is a leap month on or after month newMoon1 and
674 * at or before month newMoon2.
675 * @param newMoon1 days after January 1, 1970 0:00 astronomical base zone
677 * @param newMoon2 days after January 1, 1970 0:00 astronomical base zone
680 UBool
ChineseCalendar::isLeapMonthBetween(int32_t newMoon1
, int32_t newMoon2
) const {
682 #ifdef U_DEBUG_CHNSECAL
683 // This is only needed to debug the timeOfAngle divergence bug.
684 // Remove this later. Liu 11/9/00
685 if (synodicMonthsBetween(newMoon1
, newMoon2
) >= 50) {
686 U_DEBUG_CHNSECAL_MSG((
687 "isLeapMonthBetween(%d, %d): Invalid parameters", newMoon1
, newMoon2
692 return (newMoon2
>= newMoon1
) &&
693 (isLeapMonthBetween(newMoon1
, newMoonNear(newMoon2
- SYNODIC_GAP
, FALSE
)) ||
694 hasNoMajorSolarTerm(newMoon2
));
698 * Compute fields for the Chinese calendar system. This method can
699 * either set all relevant fields, as required by
700 * <code>handleComputeFields()</code>, or it can just set the MONTH and
701 * IS_LEAP_MONTH fields, as required by
702 * <code>handleComputeMonthStart()</code>.
704 * <p>As a side effect, this method sets {@link #isLeapYear}.
705 * @param days days after January 1, 1970 0:00 astronomical base zone
706 * of the date to compute fields for
707 * @param gyear the Gregorian year of the given date
708 * @param gmonth the Gregorian month of the given date
709 * @param setAllFields if true, set the EXTENDED_YEAR, ERA, YEAR,
710 * DAY_OF_MONTH, and DAY_OF_YEAR fields. In either case set the MONTH
711 * and IS_LEAP_MONTH fields.
713 void ChineseCalendar::computeChineseFields(int32_t days
, int32_t gyear
, int32_t gmonth
,
714 UBool setAllFields
) {
716 // Find the winter solstices before and after the target date.
717 // These define the boundaries of this Chinese year, specifically,
718 // the position of month 11, which always contains the solstice.
719 // We want solsticeBefore <= date < solsticeAfter.
720 int32_t solsticeBefore
;
721 int32_t solsticeAfter
= winterSolstice(gyear
);
722 if (days
< solsticeAfter
) {
723 solsticeBefore
= winterSolstice(gyear
- 1);
725 solsticeBefore
= solsticeAfter
;
726 solsticeAfter
= winterSolstice(gyear
+ 1);
729 // Find the start of the month after month 11. This will be either
730 // the prior month 12 or leap month 11 (very rare). Also find the
731 // start of the following month 11.
732 int32_t firstMoon
= newMoonNear(solsticeBefore
+ 1, TRUE
);
733 int32_t lastMoon
= newMoonNear(solsticeAfter
+ 1, FALSE
);
734 int32_t thisMoon
= newMoonNear(days
+ 1, FALSE
); // Start of this month
735 // Note: isLeapYear is a member variable
736 isLeapYear
= synodicMonthsBetween(firstMoon
, lastMoon
) == 12;
738 int32_t month
= synodicMonthsBetween(firstMoon
, thisMoon
);
739 if (isLeapYear
&& isLeapMonthBetween(firstMoon
, thisMoon
)) {
746 UBool isLeapMonth
= isLeapYear
&&
747 hasNoMajorSolarTerm(thisMoon
) &&
748 !isLeapMonthBetween(firstMoon
, newMoonNear(thisMoon
- SYNODIC_GAP
, FALSE
));
750 internalSet(UCAL_MONTH
, month
-1); // Convert from 1-based to 0-based
751 internalSet(UCAL_IS_LEAP_MONTH
, isLeapMonth
?1:0);
755 // Extended year and cycle year is based on the epoch year
757 int32_t extended_year
= gyear
- fEpochYear
;
758 int cycle_year
= gyear
- CHINESE_EPOCH_YEAR
;
760 gmonth
>= UCAL_JULY
) {
764 int32_t dayOfMonth
= days
- thisMoon
+ 1;
766 internalSet(UCAL_EXTENDED_YEAR
, extended_year
);
768 // 0->0,60 1->1,1 60->1,60 61->2,1 etc.
770 int32_t cycle
= ClockMath::floorDivide(cycle_year
- 1, 60, yearOfCycle
);
771 internalSet(UCAL_ERA
, cycle
+ 1);
772 internalSet(UCAL_YEAR
, yearOfCycle
+ 1);
774 internalSet(UCAL_DAY_OF_MONTH
, dayOfMonth
);
776 // Days will be before the first new year we compute if this
777 // date is in month 11, leap 11, 12. There is never a leap 12.
778 // New year computations are cached so this should be cheap in
780 int32_t theNewYear
= newYear(gyear
);
781 if (days
< theNewYear
) {
782 theNewYear
= newYear(gyear
-1);
784 internalSet(UCAL_DAY_OF_YEAR
, days
- theNewYear
+ 1);
789 //------------------------------------------------------------------
791 //------------------------------------------------------------------
793 // for gyear 1900 through 2100, corrections to linear estimate of newYear
794 static const int8_t newYearAdj
[] = {
795 -5, 14, 3, -7, 11, -1, -11, 8, -3, -14, 5, -6, 13, 1, -10, 9, -1, -13, 6, -4, // 1900-1919
796 15, 3, -8, 11, 0, -12, 8, -3, -13, 5, -6, 12, 1, -10, 9, -1, -12, 6, -5, 14, // 1920-1939
797 3, -9, 10, 0, -11, 9, -3, -14, 5, -6, 12, 1, -9, 10, -2, -12, 7, -4, 13, 3, // 1940-1959
798 -8, 11, 0, -11, 8, -2, -15, 4, -6, 13, 1, -9, 10, -1, -13, 6, -5, 14, 2, -8, // 1960-1979
799 11, 1, -11, 8, -3, 16, 5, -7, 12, 2, -8, 10, -1, -12, 6, -5, 14, 3, -7, 11, // 1980-1999
800 0, -11, 8, -4, -14, 5, -6, 13, 2, -9, 10, -2, -13, 6, -4, 14, 3, -7, 12, 0, // 2000-2019
801 -11, 8, -3, -14, 5, -6, 13, 2, -10, 9, -1, -12, 6, -4, 15, 4, -8, 11, 0, -11, // 2020-2039
802 7, -3, -13, 6, -6, 13, 2, -9, 9, -2, -12, 7, -4, 15, 4, -7, 10, 0, -11, 8, // 2040-2059
803 -3, -14, 5, -6, 12, 1, -9, 10, -1, -12, 7, -4, 15, 3, -8, 11, 1, -11, 8, -2, // 2060-2079
804 -13, 5, -6, 13, 2, -9, 10, -1, -11, 6, -5, 14, 3, -8, 11, 1, -10, 8, -3, -14, // 2080-2099
809 * Return the Chinese new year of the given Gregorian year.
810 * @param gyear a Gregorian year
811 * @return days after January 1, 1970 0:00 astronomical base zone of the
812 * Chinese new year of the given year (this will be a new moon)
814 int32_t ChineseCalendar::newYear(int32_t gyear
) const {
815 if (gyear
>= 1900 && gyear
<= 2100) {
816 // Don't use cache, just return linear estimate + table correction
817 int32_t gyearadj
= gyear
- 1900;
818 return (int32_t)(365.244*((double)gyearadj
)) - 25532 + newYearAdj
[gyearadj
];
821 UErrorCode status
= U_ZERO_ERROR
;
822 int32_t cacheValue
= CalendarCache::get(&gChineseCalendarNewYearCache
, gyear
, status
);
824 if (cacheValue
== 0) {
826 int32_t solsticeBefore
= winterSolstice(gyear
- 1);
827 int32_t solsticeAfter
= winterSolstice(gyear
);
828 int32_t newMoon1
= newMoonNear(solsticeBefore
+ 1, TRUE
);
829 int32_t newMoon2
= newMoonNear(newMoon1
+ SYNODIC_GAP
, TRUE
);
830 int32_t newMoon11
= newMoonNear(solsticeAfter
+ 1, FALSE
);
832 if (synodicMonthsBetween(newMoon1
, newMoon11
) == 12 &&
833 (hasNoMajorSolarTerm(newMoon1
) || hasNoMajorSolarTerm(newMoon2
))) {
834 cacheValue
= newMoonNear(newMoon2
+ SYNODIC_GAP
, TRUE
);
836 cacheValue
= newMoon2
;
839 CalendarCache::put(&gChineseCalendarNewYearCache
, gyear
, cacheValue
, status
);
841 if(U_FAILURE(status
)) {
848 * Adjust this calendar to be delta months before or after a given
849 * start position, pinning the day of month if necessary. The start
850 * position is given as a local days number for the start of the month
851 * and a day-of-month. Used by add() and roll().
852 * @param newMoon the local days of the first day of the month of the
853 * start position (days after January 1, 1970 0:00 Asia/Shanghai)
854 * @param dom the 1-based day-of-month of the start position
855 * @param delta the number of months to move forward or backward from
858 void ChineseCalendar::offsetMonth(int32_t newMoon
, int32_t dom
, int32_t delta
) {
859 UErrorCode status
= U_ZERO_ERROR
;
861 // Move to the middle of the month before our target month.
862 newMoon
+= (int32_t) (CalendarAstronomer::SYNODIC_MONTH
* (delta
- 0.5));
864 // Search forward to the target month's new moon
865 newMoon
= newMoonNear(newMoon
, TRUE
);
867 // Find the target dom
868 int32_t jd
= newMoon
+ kEpochStartAsJulianDay
- 1 + dom
;
870 // Pin the dom. In this calendar all months are 29 or 30 days
871 // so pinning just means handling dom 30.
873 set(UCAL_JULIAN_DAY
, jd
-1);
874 // TODO Fix this. We really shouldn't ever have to
875 // explicitly call complete(). This is either a bug in
876 // this method, in ChineseCalendar, or in
877 // Calendar.getActualMaximum(). I suspect the last.
879 if (U_FAILURE(status
)) return;
880 if (getActualMaximum(UCAL_DAY_OF_MONTH
, status
) >= dom
) {
881 if (U_FAILURE(status
)) return;
882 set(UCAL_JULIAN_DAY
, jd
);
885 set(UCAL_JULIAN_DAY
, jd
);
891 ChineseCalendar::inDaylightTime(UErrorCode
& status
) const
893 // copied from GregorianCalendar
894 if (U_FAILURE(status
) || !getTimeZone().useDaylightTime())
897 // Force an update of the state of the Calendar.
898 ((ChineseCalendar
*)this)->complete(status
); // cast away const
900 return (UBool
)(U_SUCCESS(status
) ? (internalGet(UCAL_DST_OFFSET
) != 0) : FALSE
);
905 static UDate gSystemDefaultCenturyStart
= DBL_MIN
;
906 static int32_t gSystemDefaultCenturyStartYear
= -1;
907 static icu::UInitOnce gSystemDefaultCenturyInitOnce
= U_INITONCE_INITIALIZER
;
910 UBool
ChineseCalendar::haveDefaultCentury() const
915 UDate
ChineseCalendar::defaultCenturyStart() const
917 return internalGetDefaultCenturyStart();
920 int32_t ChineseCalendar::defaultCenturyStartYear() const
922 return internalGetDefaultCenturyStartYear();
925 static void U_CALLCONV
initializeSystemDefaultCentury()
927 // initialize systemDefaultCentury and systemDefaultCenturyYear based
928 // on the current time. They'll be set to 80 years before
930 UErrorCode status
= U_ZERO_ERROR
;
931 ChineseCalendar
calendar(Locale("@calendar=chinese"),status
);
932 if (U_SUCCESS(status
)) {
933 calendar
.setTime(Calendar::getNow(), status
);
934 calendar
.add(UCAL_YEAR
, -80, status
);
935 gSystemDefaultCenturyStart
= calendar
.getTime(status
);
936 gSystemDefaultCenturyStartYear
= calendar
.get(UCAL_YEAR
, status
);
938 // We have no recourse upon failure unless we want to propagate the failure
943 ChineseCalendar::internalGetDefaultCenturyStart() const
945 // lazy-evaluate systemDefaultCenturyStart
946 umtx_initOnce(gSystemDefaultCenturyInitOnce
, &initializeSystemDefaultCentury
);
947 return gSystemDefaultCenturyStart
;
951 ChineseCalendar::internalGetDefaultCenturyStartYear() const
953 // lazy-evaluate systemDefaultCenturyStartYear
954 umtx_initOnce(gSystemDefaultCenturyInitOnce
, &initializeSystemDefaultCentury
);
955 return gSystemDefaultCenturyStartYear
;
958 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(ChineseCalendar
)