michael@0: /* michael@0: ****************************************************************************** michael@0: * Copyright (C) 2007-2013, International Business Machines Corporation michael@0: * and others. All Rights Reserved. michael@0: ****************************************************************************** michael@0: * michael@0: * File CHNSECAL.CPP michael@0: * michael@0: * Modification History: michael@0: * michael@0: * Date Name Description michael@0: * 9/18/2007 ajmacher ported from java ChineseCalendar michael@0: ***************************************************************************** michael@0: */ michael@0: michael@0: #include "chnsecal.h" michael@0: michael@0: #if !UCONFIG_NO_FORMATTING michael@0: michael@0: #include "umutex.h" michael@0: #include michael@0: #include "gregoimp.h" // Math michael@0: #include "astro.h" // CalendarAstronomer michael@0: #include "unicode/simpletz.h" michael@0: #include "uhash.h" michael@0: #include "ucln_in.h" michael@0: michael@0: // Debugging michael@0: #ifdef U_DEBUG_CHNSECAL michael@0: # include michael@0: # include michael@0: static void debug_chnsecal_loc(const char *f, int32_t l) michael@0: { michael@0: fprintf(stderr, "%s:%d: ", f, l); michael@0: } michael@0: michael@0: static void debug_chnsecal_msg(const char *pat, ...) michael@0: { michael@0: va_list ap; michael@0: va_start(ap, pat); michael@0: vfprintf(stderr, pat, ap); michael@0: fflush(stderr); michael@0: } michael@0: // must use double parens, i.e.: U_DEBUG_CHNSECAL_MSG(("four is: %d",4)); michael@0: #define U_DEBUG_CHNSECAL_MSG(x) {debug_chnsecal_loc(__FILE__,__LINE__);debug_chnsecal_msg x;} michael@0: #else michael@0: #define U_DEBUG_CHNSECAL_MSG(x) michael@0: #endif michael@0: michael@0: michael@0: // --- The cache -- michael@0: static UMutex astroLock = U_MUTEX_INITIALIZER; // pod bay door lock michael@0: static icu::CalendarAstronomer *gChineseCalendarAstro = NULL; michael@0: static icu::CalendarCache *gChineseCalendarWinterSolsticeCache = NULL; michael@0: static icu::CalendarCache *gChineseCalendarNewYearCache = NULL; michael@0: static icu::TimeZone *gChineseCalendarZoneAstroCalc = NULL; michael@0: static icu::UInitOnce gChineseCalendarZoneAstroCalcInitOnce = U_INITONCE_INITIALIZER; michael@0: michael@0: /** michael@0: * The start year of the Chinese calendar, the 61st year of the reign michael@0: * of Huang Di. Some sources use the first year of his reign, michael@0: * resulting in EXTENDED_YEAR values 60 years greater and ERA (cycle) michael@0: * values one greater. michael@0: */ michael@0: static const int32_t CHINESE_EPOCH_YEAR = -2636; // Gregorian year michael@0: michael@0: /** michael@0: * The offset from GMT in milliseconds at which we perform astronomical michael@0: * computations. Some sources use a different historically accurate michael@0: * offset of GMT+7:45:40 for years before 1929; we do not do this. michael@0: */ michael@0: static const int32_t CHINA_OFFSET = 8 * kOneHour; michael@0: michael@0: /** michael@0: * Value to be added or subtracted from the local days of a new moon to michael@0: * get close to the next or prior new moon, but not cross it. Must be michael@0: * >= 1 and < CalendarAstronomer.SYNODIC_MONTH. michael@0: */ michael@0: static const int32_t SYNODIC_GAP = 25; michael@0: michael@0: michael@0: U_CDECL_BEGIN michael@0: static UBool calendar_chinese_cleanup(void) { michael@0: if (gChineseCalendarAstro) { michael@0: delete gChineseCalendarAstro; michael@0: gChineseCalendarAstro = NULL; michael@0: } michael@0: if (gChineseCalendarWinterSolsticeCache) { michael@0: delete gChineseCalendarWinterSolsticeCache; michael@0: gChineseCalendarWinterSolsticeCache = NULL; michael@0: } michael@0: if (gChineseCalendarNewYearCache) { michael@0: delete gChineseCalendarNewYearCache; michael@0: gChineseCalendarNewYearCache = NULL; michael@0: } michael@0: if (gChineseCalendarZoneAstroCalc) { michael@0: delete gChineseCalendarZoneAstroCalc; michael@0: gChineseCalendarZoneAstroCalc = NULL; michael@0: } michael@0: gChineseCalendarZoneAstroCalcInitOnce.reset(); michael@0: return TRUE; michael@0: } michael@0: U_CDECL_END michael@0: michael@0: U_NAMESPACE_BEGIN michael@0: michael@0: michael@0: // Implementation of the ChineseCalendar class michael@0: michael@0: michael@0: //------------------------------------------------------------------------- michael@0: // Constructors... michael@0: //------------------------------------------------------------------------- michael@0: michael@0: michael@0: Calendar* ChineseCalendar::clone() const { michael@0: return new ChineseCalendar(*this); michael@0: } michael@0: michael@0: ChineseCalendar::ChineseCalendar(const Locale& aLocale, UErrorCode& success) michael@0: : Calendar(TimeZone::createDefault(), aLocale, success), michael@0: isLeapYear(FALSE), michael@0: fEpochYear(CHINESE_EPOCH_YEAR), michael@0: fZoneAstroCalc(getChineseCalZoneAstroCalc()) michael@0: { michael@0: setTimeInMillis(getNow(), success); // Call this again now that the vtable is set up properly. michael@0: } michael@0: michael@0: ChineseCalendar::ChineseCalendar(const Locale& aLocale, int32_t epochYear, michael@0: const TimeZone* zoneAstroCalc, UErrorCode &success) michael@0: : Calendar(TimeZone::createDefault(), aLocale, success), michael@0: isLeapYear(FALSE), michael@0: fEpochYear(epochYear), michael@0: fZoneAstroCalc(zoneAstroCalc) michael@0: { michael@0: setTimeInMillis(getNow(), success); // Call this again now that the vtable is set up properly. michael@0: } michael@0: michael@0: ChineseCalendar::ChineseCalendar(const ChineseCalendar& other) : Calendar(other) { michael@0: isLeapYear = other.isLeapYear; michael@0: fEpochYear = other.fEpochYear; michael@0: fZoneAstroCalc = other.fZoneAstroCalc; michael@0: } michael@0: michael@0: ChineseCalendar::~ChineseCalendar() michael@0: { michael@0: } michael@0: michael@0: const char *ChineseCalendar::getType() const { michael@0: return "chinese"; michael@0: } michael@0: michael@0: static void U_CALLCONV initChineseCalZoneAstroCalc() { michael@0: gChineseCalendarZoneAstroCalc = new SimpleTimeZone(CHINA_OFFSET, UNICODE_STRING_SIMPLE("CHINA_ZONE") ); michael@0: ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR, calendar_chinese_cleanup); michael@0: } michael@0: michael@0: const TimeZone* ChineseCalendar::getChineseCalZoneAstroCalc(void) const { michael@0: umtx_initOnce(gChineseCalendarZoneAstroCalcInitOnce, &initChineseCalZoneAstroCalc); michael@0: return gChineseCalendarZoneAstroCalc; michael@0: } michael@0: michael@0: //------------------------------------------------------------------------- michael@0: // Minimum / Maximum access functions michael@0: //------------------------------------------------------------------------- michael@0: michael@0: michael@0: static const int32_t LIMITS[UCAL_FIELD_COUNT][4] = { michael@0: // Minimum Greatest Least Maximum michael@0: // Minimum Maximum michael@0: { 1, 1, 83333, 83333}, // ERA michael@0: { 1, 1, 60, 60}, // YEAR michael@0: { 0, 0, 11, 11}, // MONTH michael@0: { 1, 1, 50, 55}, // WEEK_OF_YEAR michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // WEEK_OF_MONTH michael@0: { 1, 1, 29, 30}, // DAY_OF_MONTH michael@0: { 1, 1, 353, 385}, // DAY_OF_YEAR michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK michael@0: { -1, -1, 5, 5}, // DAY_OF_WEEK_IN_MONTH michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET michael@0: { -5000000, -5000000, 5000000, 5000000}, // YEAR_WOY michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL michael@0: { -5000000, -5000000, 5000000, 5000000}, // EXTENDED_YEAR michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY michael@0: {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECONDS_IN_DAY michael@0: { 0, 0, 1, 1}, // IS_LEAP_MONTH michael@0: }; michael@0: michael@0: michael@0: /** michael@0: * @draft ICU 2.4 michael@0: */ michael@0: int32_t ChineseCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const { michael@0: return LIMITS[field][limitType]; michael@0: } michael@0: michael@0: michael@0: //---------------------------------------------------------------------- michael@0: // Calendar framework michael@0: //---------------------------------------------------------------------- michael@0: michael@0: /** michael@0: * Implement abstract Calendar method to return the extended year michael@0: * defined by the current fields. This will use either the ERA and michael@0: * YEAR field as the cycle and year-of-cycle, or the EXTENDED_YEAR michael@0: * field as the continuous year count, depending on which is newer. michael@0: * @stable ICU 2.8 michael@0: */ michael@0: int32_t ChineseCalendar::handleGetExtendedYear() { michael@0: int32_t year; michael@0: if (newestStamp(UCAL_ERA, UCAL_YEAR, kUnset) <= fStamp[UCAL_EXTENDED_YEAR]) { michael@0: year = internalGet(UCAL_EXTENDED_YEAR, 1); // Default to year 1 michael@0: } else { michael@0: int32_t cycle = internalGet(UCAL_ERA, 1) - 1; // 0-based cycle michael@0: // adjust to the instance specific epoch michael@0: year = cycle * 60 + internalGet(UCAL_YEAR, 1) - (fEpochYear - CHINESE_EPOCH_YEAR); michael@0: } michael@0: return year; michael@0: } michael@0: michael@0: /** michael@0: * Override Calendar method to return the number of days in the given michael@0: * extended year and month. michael@0: * michael@0: *

Note: This method also reads the IS_LEAP_MONTH field to determine michael@0: * whether or not the given month is a leap month. michael@0: * @stable ICU 2.8 michael@0: */ michael@0: int32_t ChineseCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month) const { michael@0: int32_t thisStart = handleComputeMonthStart(extendedYear, month, TRUE) - michael@0: kEpochStartAsJulianDay + 1; // Julian day -> local days michael@0: int32_t nextStart = newMoonNear(thisStart + SYNODIC_GAP, TRUE); michael@0: return nextStart - thisStart; michael@0: } michael@0: michael@0: /** michael@0: * Override Calendar to compute several fields specific to the Chinese michael@0: * calendar system. These are: michael@0: * michael@0: *

  • ERA michael@0: *
  • YEAR michael@0: *
  • MONTH michael@0: *
  • DAY_OF_MONTH michael@0: *
  • DAY_OF_YEAR michael@0: *
  • EXTENDED_YEAR
michael@0: * michael@0: * The DAY_OF_WEEK and DOW_LOCAL fields are already set when this michael@0: * method is called. The getGregorianXxx() methods return Gregorian michael@0: * calendar equivalents for the given Julian day. michael@0: * michael@0: *

Compute the ChineseCalendar-specific field IS_LEAP_MONTH. michael@0: * @stable ICU 2.8 michael@0: */ michael@0: void ChineseCalendar::handleComputeFields(int32_t julianDay, UErrorCode &/*status*/) { michael@0: michael@0: computeChineseFields(julianDay - kEpochStartAsJulianDay, // local days michael@0: getGregorianYear(), getGregorianMonth(), michael@0: TRUE); // set all fields michael@0: } michael@0: michael@0: /** michael@0: * Field resolution table that incorporates IS_LEAP_MONTH. michael@0: */ michael@0: const UFieldResolutionTable ChineseCalendar::CHINESE_DATE_PRECEDENCE[] = michael@0: { michael@0: { michael@0: { UCAL_DAY_OF_MONTH, kResolveSTOP }, michael@0: { UCAL_WEEK_OF_YEAR, UCAL_DAY_OF_WEEK, kResolveSTOP }, michael@0: { UCAL_WEEK_OF_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP }, michael@0: { UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP }, michael@0: { UCAL_WEEK_OF_YEAR, UCAL_DOW_LOCAL, kResolveSTOP }, michael@0: { UCAL_WEEK_OF_MONTH, UCAL_DOW_LOCAL, kResolveSTOP }, michael@0: { UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP }, michael@0: { UCAL_DAY_OF_YEAR, kResolveSTOP }, michael@0: { kResolveRemap | UCAL_DAY_OF_MONTH, UCAL_IS_LEAP_MONTH, kResolveSTOP }, michael@0: { kResolveSTOP } michael@0: }, michael@0: { michael@0: { UCAL_WEEK_OF_YEAR, kResolveSTOP }, michael@0: { UCAL_WEEK_OF_MONTH, kResolveSTOP }, michael@0: { UCAL_DAY_OF_WEEK_IN_MONTH, kResolveSTOP }, michael@0: { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP }, michael@0: { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP }, michael@0: { kResolveSTOP } michael@0: }, michael@0: {{kResolveSTOP}} michael@0: }; michael@0: michael@0: /** michael@0: * Override Calendar to add IS_LEAP_MONTH to the field resolution michael@0: * table. michael@0: * @stable ICU 2.8 michael@0: */ michael@0: const UFieldResolutionTable* ChineseCalendar::getFieldResolutionTable() const { michael@0: return CHINESE_DATE_PRECEDENCE; michael@0: } michael@0: michael@0: /** michael@0: * Return the Julian day number of day before the first day of the michael@0: * given month in the given extended year. michael@0: * michael@0: *

Note: This method reads the IS_LEAP_MONTH field to determine michael@0: * whether the given month is a leap month. michael@0: * @param eyear the extended year michael@0: * @param month the zero-based month. The month is also determined michael@0: * by reading the IS_LEAP_MONTH field. michael@0: * @return the Julian day number of the day before the first michael@0: * day of the given month and year michael@0: * @stable ICU 2.8 michael@0: */ michael@0: int32_t ChineseCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool useMonth) const { michael@0: michael@0: ChineseCalendar *nonConstThis = (ChineseCalendar*)this; // cast away const michael@0: michael@0: // If the month is out of range, adjust it into range, and michael@0: // modify the extended year value accordingly. michael@0: if (month < 0 || month > 11) { michael@0: double m = month; michael@0: eyear += (int32_t)ClockMath::floorDivide(m, 12.0, m); michael@0: month = (int32_t)m; michael@0: } michael@0: michael@0: int32_t gyear = eyear + fEpochYear - 1; // Gregorian year michael@0: int32_t theNewYear = newYear(gyear); michael@0: int32_t newMoon = newMoonNear(theNewYear + month * 29, TRUE); michael@0: michael@0: int32_t julianDay = newMoon + kEpochStartAsJulianDay; michael@0: michael@0: // Save fields for later restoration michael@0: int32_t saveMonth = internalGet(UCAL_MONTH); michael@0: int32_t saveIsLeapMonth = internalGet(UCAL_IS_LEAP_MONTH); michael@0: michael@0: // Ignore IS_LEAP_MONTH field if useMonth is false michael@0: int32_t isLeapMonth = useMonth ? saveIsLeapMonth : 0; michael@0: michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: nonConstThis->computeGregorianFields(julianDay, status); michael@0: if (U_FAILURE(status)) michael@0: return 0; michael@0: michael@0: // This will modify the MONTH and IS_LEAP_MONTH fields (only) michael@0: nonConstThis->computeChineseFields(newMoon, getGregorianYear(), michael@0: getGregorianMonth(), FALSE); michael@0: michael@0: if (month != internalGet(UCAL_MONTH) || michael@0: isLeapMonth != internalGet(UCAL_IS_LEAP_MONTH)) { michael@0: newMoon = newMoonNear(newMoon + SYNODIC_GAP, TRUE); michael@0: julianDay = newMoon + kEpochStartAsJulianDay; michael@0: } michael@0: michael@0: nonConstThis->internalSet(UCAL_MONTH, saveMonth); michael@0: nonConstThis->internalSet(UCAL_IS_LEAP_MONTH, saveIsLeapMonth); michael@0: michael@0: return julianDay - 1; michael@0: } michael@0: michael@0: michael@0: /** michael@0: * Override Calendar to handle leap months properly. michael@0: * @stable ICU 2.8 michael@0: */ michael@0: void ChineseCalendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& status) { michael@0: switch (field) { michael@0: case UCAL_MONTH: michael@0: if (amount != 0) { michael@0: int32_t dom = get(UCAL_DAY_OF_MONTH, status); michael@0: if (U_FAILURE(status)) break; michael@0: int32_t day = get(UCAL_JULIAN_DAY, status) - kEpochStartAsJulianDay; // Get local day michael@0: if (U_FAILURE(status)) break; michael@0: int32_t moon = day - dom + 1; // New moon michael@0: offsetMonth(moon, dom, amount); michael@0: } michael@0: break; michael@0: default: michael@0: Calendar::add(field, amount, status); michael@0: break; michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Override Calendar to handle leap months properly. michael@0: * @stable ICU 2.8 michael@0: */ michael@0: void ChineseCalendar::add(EDateFields field, int32_t amount, UErrorCode& status) { michael@0: add((UCalendarDateFields)field, amount, status); michael@0: } michael@0: michael@0: /** michael@0: * Override Calendar to handle leap months properly. michael@0: * @stable ICU 2.8 michael@0: */ michael@0: void ChineseCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) { michael@0: switch (field) { michael@0: case UCAL_MONTH: michael@0: if (amount != 0) { michael@0: int32_t dom = get(UCAL_DAY_OF_MONTH, status); michael@0: if (U_FAILURE(status)) break; michael@0: int32_t day = get(UCAL_JULIAN_DAY, status) - kEpochStartAsJulianDay; // Get local day michael@0: if (U_FAILURE(status)) break; michael@0: int32_t moon = day - dom + 1; // New moon (start of this month) michael@0: michael@0: // Note throughout the following: Months 12 and 1 are never michael@0: // followed by a leap month (D&R p. 185). michael@0: michael@0: // Compute the adjusted month number m. This is zero-based michael@0: // value from 0..11 in a non-leap year, and from 0..12 in a michael@0: // leap year. michael@0: int32_t m = get(UCAL_MONTH, status); // 0-based month michael@0: if (U_FAILURE(status)) break; michael@0: if (isLeapYear) { // (member variable) michael@0: if (get(UCAL_IS_LEAP_MONTH, status) == 1) { michael@0: ++m; michael@0: } else { michael@0: // Check for a prior leap month. (In the michael@0: // following, month 0 is the first month of the michael@0: // year.) Month 0 is never followed by a leap michael@0: // month, and we know month m is not a leap month. michael@0: // moon1 will be the start of month 0 if there is michael@0: // no leap month between month 0 and month m; michael@0: // otherwise it will be the start of month 1. michael@0: int moon1 = moon - michael@0: (int) (CalendarAstronomer::SYNODIC_MONTH * (m - 0.5)); michael@0: moon1 = newMoonNear(moon1, TRUE); michael@0: if (isLeapMonthBetween(moon1, moon)) { michael@0: ++m; michael@0: } michael@0: } michael@0: if (U_FAILURE(status)) break; michael@0: } michael@0: michael@0: // Now do the standard roll computation on m, with the michael@0: // allowed range of 0..n-1, where n is 12 or 13. michael@0: int32_t n = isLeapYear ? 13 : 12; // Months in this year michael@0: int32_t newM = (m + amount) % n; michael@0: if (newM < 0) { michael@0: newM += n; michael@0: } michael@0: michael@0: if (newM != m) { michael@0: offsetMonth(moon, dom, newM - m); michael@0: } michael@0: } michael@0: break; michael@0: default: michael@0: Calendar::roll(field, amount, status); michael@0: break; michael@0: } michael@0: } michael@0: michael@0: void ChineseCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) { michael@0: roll((UCalendarDateFields)field, amount, status); michael@0: } michael@0: michael@0: michael@0: //------------------------------------------------------------------ michael@0: // Support methods and constants michael@0: //------------------------------------------------------------------ michael@0: michael@0: /** michael@0: * Convert local days to UTC epoch milliseconds. michael@0: * This is not an accurate conversion in that getTimezoneOffset michael@0: * takes the milliseconds in GMT (not local time). In theory, more michael@0: * accurate algorithm can be implemented but practically we do not need michael@0: * to go through that complication as long as the historical timezone michael@0: * changes did not happen around the 'tricky' new moon (new moon around michael@0: * midnight). michael@0: * michael@0: * @param days days after January 1, 1970 0:00 in the astronomical base zone michael@0: * @return milliseconds after January 1, 1970 0:00 GMT michael@0: */ michael@0: double ChineseCalendar::daysToMillis(double days) const { michael@0: double millis = days * (double)kOneDay; michael@0: if (fZoneAstroCalc != NULL) { michael@0: int32_t rawOffset, dstOffset; michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: fZoneAstroCalc->getOffset(millis, FALSE, rawOffset, dstOffset, status); michael@0: if (U_SUCCESS(status)) { michael@0: return millis - (double)(rawOffset + dstOffset); michael@0: } michael@0: } michael@0: return millis - (double)CHINA_OFFSET; michael@0: } michael@0: michael@0: /** michael@0: * Convert UTC epoch milliseconds to local days. michael@0: * @param millis milliseconds after January 1, 1970 0:00 GMT michael@0: * @return days after January 1, 1970 0:00 in the astronomical base zone michael@0: */ michael@0: double ChineseCalendar::millisToDays(double millis) const { michael@0: if (fZoneAstroCalc != NULL) { michael@0: int32_t rawOffset, dstOffset; michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: fZoneAstroCalc->getOffset(millis, FALSE, rawOffset, dstOffset, status); michael@0: if (U_SUCCESS(status)) { michael@0: return ClockMath::floorDivide(millis + (double)(rawOffset + dstOffset), kOneDay); michael@0: } michael@0: } michael@0: return ClockMath::floorDivide(millis + (double)CHINA_OFFSET, kOneDay); michael@0: } michael@0: michael@0: //------------------------------------------------------------------ michael@0: // Astronomical computations michael@0: //------------------------------------------------------------------ michael@0: michael@0: michael@0: /** michael@0: * Return the major solar term on or after December 15 of the given michael@0: * Gregorian year, that is, the winter solstice of the given year. michael@0: * Computations are relative to Asia/Shanghai time zone. michael@0: * @param gyear a Gregorian year michael@0: * @return days after January 1, 1970 0:00 Asia/Shanghai of the michael@0: * winter solstice of the given year michael@0: */ michael@0: int32_t ChineseCalendar::winterSolstice(int32_t gyear) const { michael@0: michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: int32_t cacheValue = CalendarCache::get(&gChineseCalendarWinterSolsticeCache, gyear, status); michael@0: michael@0: if (cacheValue == 0) { michael@0: // In books December 15 is used, but it fails for some years michael@0: // using our algorithms, e.g.: 1298 1391 1492 1553 1560. That michael@0: // is, winterSolstice(1298) starts search at Dec 14 08:00:00 michael@0: // PST 1298 with a final result of Dec 14 10:31:59 PST 1299. michael@0: double ms = daysToMillis(Grego::fieldsToDay(gyear, UCAL_DECEMBER, 1)); michael@0: michael@0: umtx_lock(&astroLock); michael@0: if(gChineseCalendarAstro == NULL) { michael@0: gChineseCalendarAstro = new CalendarAstronomer(); michael@0: ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR, calendar_chinese_cleanup); michael@0: } michael@0: gChineseCalendarAstro->setTime(ms); michael@0: UDate solarLong = gChineseCalendarAstro->getSunTime(CalendarAstronomer::WINTER_SOLSTICE(), TRUE); michael@0: umtx_unlock(&astroLock); michael@0: michael@0: // Winter solstice is 270 degrees solar longitude aka Dongzhi michael@0: cacheValue = (int32_t)millisToDays(solarLong); michael@0: CalendarCache::put(&gChineseCalendarWinterSolsticeCache, gyear, cacheValue, status); michael@0: } michael@0: if(U_FAILURE(status)) { michael@0: cacheValue = 0; michael@0: } michael@0: return cacheValue; michael@0: } michael@0: michael@0: /** michael@0: * Return the closest new moon to the given date, searching either michael@0: * forward or backward in time. michael@0: * @param days days after January 1, 1970 0:00 Asia/Shanghai michael@0: * @param after if true, search for a new moon on or after the given michael@0: * date; otherwise, search for a new moon before it michael@0: * @return days after January 1, 1970 0:00 Asia/Shanghai of the nearest michael@0: * new moon after or before days michael@0: */ michael@0: int32_t ChineseCalendar::newMoonNear(double days, UBool after) const { michael@0: michael@0: umtx_lock(&astroLock); michael@0: if(gChineseCalendarAstro == NULL) { michael@0: gChineseCalendarAstro = new CalendarAstronomer(); michael@0: ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR, calendar_chinese_cleanup); michael@0: } michael@0: gChineseCalendarAstro->setTime(daysToMillis(days)); michael@0: UDate newMoon = gChineseCalendarAstro->getMoonTime(CalendarAstronomer::NEW_MOON(), after); michael@0: umtx_unlock(&astroLock); michael@0: michael@0: return (int32_t) millisToDays(newMoon); michael@0: } michael@0: michael@0: /** michael@0: * Return the nearest integer number of synodic months between michael@0: * two dates. michael@0: * @param day1 days after January 1, 1970 0:00 Asia/Shanghai michael@0: * @param day2 days after January 1, 1970 0:00 Asia/Shanghai michael@0: * @return the nearest integer number of months between day1 and day2 michael@0: */ michael@0: int32_t ChineseCalendar::synodicMonthsBetween(int32_t day1, int32_t day2) const { michael@0: double roundme = ((day2 - day1) / CalendarAstronomer::SYNODIC_MONTH); michael@0: return (int32_t) (roundme + (roundme >= 0 ? .5 : -.5)); michael@0: } michael@0: michael@0: /** michael@0: * Return the major solar term on or before a given date. This michael@0: * will be an integer from 1..12, with 1 corresponding to 330 degrees, michael@0: * 2 to 0 degrees, 3 to 30 degrees,..., and 12 to 300 degrees. michael@0: * @param days days after January 1, 1970 0:00 Asia/Shanghai michael@0: */ michael@0: int32_t ChineseCalendar::majorSolarTerm(int32_t days) const { michael@0: michael@0: umtx_lock(&astroLock); michael@0: if(gChineseCalendarAstro == NULL) { michael@0: gChineseCalendarAstro = new CalendarAstronomer(); michael@0: ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR, calendar_chinese_cleanup); michael@0: } michael@0: gChineseCalendarAstro->setTime(daysToMillis(days)); michael@0: UDate solarLongitude = gChineseCalendarAstro->getSunLongitude(); michael@0: umtx_unlock(&astroLock); michael@0: michael@0: // Compute (floor(solarLongitude / (pi/6)) + 2) % 12 michael@0: int32_t term = ( ((int32_t)(6 * solarLongitude / CalendarAstronomer::PI)) + 2 ) % 12; michael@0: if (term < 1) { michael@0: term += 12; michael@0: } michael@0: return term; michael@0: } michael@0: michael@0: /** michael@0: * Return true if the given month lacks a major solar term. michael@0: * @param newMoon days after January 1, 1970 0:00 Asia/Shanghai of a new michael@0: * moon michael@0: */ michael@0: UBool ChineseCalendar::hasNoMajorSolarTerm(int32_t newMoon) const { michael@0: return majorSolarTerm(newMoon) == michael@0: majorSolarTerm(newMoonNear(newMoon + SYNODIC_GAP, TRUE)); michael@0: } michael@0: michael@0: michael@0: //------------------------------------------------------------------ michael@0: // Time to fields michael@0: //------------------------------------------------------------------ michael@0: michael@0: /** michael@0: * Return true if there is a leap month on or after month newMoon1 and michael@0: * at or before month newMoon2. michael@0: * @param newMoon1 days after January 1, 1970 0:00 astronomical base zone michael@0: * of a new moon michael@0: * @param newMoon2 days after January 1, 1970 0:00 astronomical base zone michael@0: * of a new moon michael@0: */ michael@0: UBool ChineseCalendar::isLeapMonthBetween(int32_t newMoon1, int32_t newMoon2) const { michael@0: michael@0: #ifdef U_DEBUG_CHNSECAL michael@0: // This is only needed to debug the timeOfAngle divergence bug. michael@0: // Remove this later. Liu 11/9/00 michael@0: if (synodicMonthsBetween(newMoon1, newMoon2) >= 50) { michael@0: U_DEBUG_CHNSECAL_MSG(( michael@0: "isLeapMonthBetween(%d, %d): Invalid parameters", newMoon1, newMoon2 michael@0: )); michael@0: } michael@0: #endif michael@0: michael@0: return (newMoon2 >= newMoon1) && michael@0: (isLeapMonthBetween(newMoon1, newMoonNear(newMoon2 - SYNODIC_GAP, FALSE)) || michael@0: hasNoMajorSolarTerm(newMoon2)); michael@0: } michael@0: michael@0: /** michael@0: * Compute fields for the Chinese calendar system. This method can michael@0: * either set all relevant fields, as required by michael@0: * handleComputeFields(), or it can just set the MONTH and michael@0: * IS_LEAP_MONTH fields, as required by michael@0: * handleComputeMonthStart(). michael@0: * michael@0: *

As a side effect, this method sets {@link #isLeapYear}. michael@0: * @param days days after January 1, 1970 0:00 astronomical base zone michael@0: * of the date to compute fields for michael@0: * @param gyear the Gregorian year of the given date michael@0: * @param gmonth the Gregorian month of the given date michael@0: * @param setAllFields if true, set the EXTENDED_YEAR, ERA, YEAR, michael@0: * DAY_OF_MONTH, and DAY_OF_YEAR fields. In either case set the MONTH michael@0: * and IS_LEAP_MONTH fields. michael@0: */ michael@0: void ChineseCalendar::computeChineseFields(int32_t days, int32_t gyear, int32_t gmonth, michael@0: UBool setAllFields) { michael@0: michael@0: // Find the winter solstices before and after the target date. michael@0: // These define the boundaries of this Chinese year, specifically, michael@0: // the position of month 11, which always contains the solstice. michael@0: // We want solsticeBefore <= date < solsticeAfter. michael@0: int32_t solsticeBefore; michael@0: int32_t solsticeAfter = winterSolstice(gyear); michael@0: if (days < solsticeAfter) { michael@0: solsticeBefore = winterSolstice(gyear - 1); michael@0: } else { michael@0: solsticeBefore = solsticeAfter; michael@0: solsticeAfter = winterSolstice(gyear + 1); michael@0: } michael@0: michael@0: // Find the start of the month after month 11. This will be either michael@0: // the prior month 12 or leap month 11 (very rare). Also find the michael@0: // start of the following month 11. michael@0: int32_t firstMoon = newMoonNear(solsticeBefore + 1, TRUE); michael@0: int32_t lastMoon = newMoonNear(solsticeAfter + 1, FALSE); michael@0: int32_t thisMoon = newMoonNear(days + 1, FALSE); // Start of this month michael@0: // Note: isLeapYear is a member variable michael@0: isLeapYear = synodicMonthsBetween(firstMoon, lastMoon) == 12; michael@0: michael@0: int32_t month = synodicMonthsBetween(firstMoon, thisMoon); michael@0: if (isLeapYear && isLeapMonthBetween(firstMoon, thisMoon)) { michael@0: month--; michael@0: } michael@0: if (month < 1) { michael@0: month += 12; michael@0: } michael@0: michael@0: UBool isLeapMonth = isLeapYear && michael@0: hasNoMajorSolarTerm(thisMoon) && michael@0: !isLeapMonthBetween(firstMoon, newMoonNear(thisMoon - SYNODIC_GAP, FALSE)); michael@0: michael@0: internalSet(UCAL_MONTH, month-1); // Convert from 1-based to 0-based michael@0: internalSet(UCAL_IS_LEAP_MONTH, isLeapMonth?1:0); michael@0: michael@0: if (setAllFields) { michael@0: michael@0: // Extended year and cycle year is based on the epoch year michael@0: michael@0: int32_t extended_year = gyear - fEpochYear; michael@0: int cycle_year = gyear - CHINESE_EPOCH_YEAR; michael@0: if (month < 11 || michael@0: gmonth >= UCAL_JULY) { michael@0: extended_year++; michael@0: cycle_year++; michael@0: } michael@0: int32_t dayOfMonth = days - thisMoon + 1; michael@0: michael@0: internalSet(UCAL_EXTENDED_YEAR, extended_year); michael@0: michael@0: // 0->0,60 1->1,1 60->1,60 61->2,1 etc. michael@0: int32_t yearOfCycle; michael@0: int32_t cycle = ClockMath::floorDivide(cycle_year - 1, 60, yearOfCycle); michael@0: internalSet(UCAL_ERA, cycle + 1); michael@0: internalSet(UCAL_YEAR, yearOfCycle + 1); michael@0: michael@0: internalSet(UCAL_DAY_OF_MONTH, dayOfMonth); michael@0: michael@0: // Days will be before the first new year we compute if this michael@0: // date is in month 11, leap 11, 12. There is never a leap 12. michael@0: // New year computations are cached so this should be cheap in michael@0: // the long run. michael@0: int32_t theNewYear = newYear(gyear); michael@0: if (days < theNewYear) { michael@0: theNewYear = newYear(gyear-1); michael@0: } michael@0: internalSet(UCAL_DAY_OF_YEAR, days - theNewYear + 1); michael@0: } michael@0: } michael@0: michael@0: michael@0: //------------------------------------------------------------------ michael@0: // Fields to time michael@0: //------------------------------------------------------------------ michael@0: michael@0: /** michael@0: * Return the Chinese new year of the given Gregorian year. michael@0: * @param gyear a Gregorian year michael@0: * @return days after January 1, 1970 0:00 astronomical base zone of the michael@0: * Chinese new year of the given year (this will be a new moon) michael@0: */ michael@0: int32_t ChineseCalendar::newYear(int32_t gyear) const { michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: int32_t cacheValue = CalendarCache::get(&gChineseCalendarNewYearCache, gyear, status); michael@0: michael@0: if (cacheValue == 0) { michael@0: michael@0: int32_t solsticeBefore= winterSolstice(gyear - 1); michael@0: int32_t solsticeAfter = winterSolstice(gyear); michael@0: int32_t newMoon1 = newMoonNear(solsticeBefore + 1, TRUE); michael@0: int32_t newMoon2 = newMoonNear(newMoon1 + SYNODIC_GAP, TRUE); michael@0: int32_t newMoon11 = newMoonNear(solsticeAfter + 1, FALSE); michael@0: michael@0: if (synodicMonthsBetween(newMoon1, newMoon11) == 12 && michael@0: (hasNoMajorSolarTerm(newMoon1) || hasNoMajorSolarTerm(newMoon2))) { michael@0: cacheValue = newMoonNear(newMoon2 + SYNODIC_GAP, TRUE); michael@0: } else { michael@0: cacheValue = newMoon2; michael@0: } michael@0: michael@0: CalendarCache::put(&gChineseCalendarNewYearCache, gyear, cacheValue, status); michael@0: } michael@0: if(U_FAILURE(status)) { michael@0: cacheValue = 0; michael@0: } michael@0: return cacheValue; michael@0: } michael@0: michael@0: /** michael@0: * Adjust this calendar to be delta months before or after a given michael@0: * start position, pinning the day of month if necessary. The start michael@0: * position is given as a local days number for the start of the month michael@0: * and a day-of-month. Used by add() and roll(). michael@0: * @param newMoon the local days of the first day of the month of the michael@0: * start position (days after January 1, 1970 0:00 Asia/Shanghai) michael@0: * @param dom the 1-based day-of-month of the start position michael@0: * @param delta the number of months to move forward or backward from michael@0: * the start position michael@0: */ michael@0: void ChineseCalendar::offsetMonth(int32_t newMoon, int32_t dom, int32_t delta) { michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: michael@0: // Move to the middle of the month before our target month. michael@0: newMoon += (int32_t) (CalendarAstronomer::SYNODIC_MONTH * (delta - 0.5)); michael@0: michael@0: // Search forward to the target month's new moon michael@0: newMoon = newMoonNear(newMoon, TRUE); michael@0: michael@0: // Find the target dom michael@0: int32_t jd = newMoon + kEpochStartAsJulianDay - 1 + dom; michael@0: michael@0: // Pin the dom. In this calendar all months are 29 or 30 days michael@0: // so pinning just means handling dom 30. michael@0: if (dom > 29) { michael@0: set(UCAL_JULIAN_DAY, jd-1); michael@0: // TODO Fix this. We really shouldn't ever have to michael@0: // explicitly call complete(). This is either a bug in michael@0: // this method, in ChineseCalendar, or in michael@0: // Calendar.getActualMaximum(). I suspect the last. michael@0: complete(status); michael@0: if (U_FAILURE(status)) return; michael@0: if (getActualMaximum(UCAL_DAY_OF_MONTH, status) >= dom) { michael@0: if (U_FAILURE(status)) return; michael@0: set(UCAL_JULIAN_DAY, jd); michael@0: } michael@0: } else { michael@0: set(UCAL_JULIAN_DAY, jd); michael@0: } michael@0: } michael@0: michael@0: michael@0: UBool michael@0: ChineseCalendar::inDaylightTime(UErrorCode& status) const michael@0: { michael@0: // copied from GregorianCalendar michael@0: if (U_FAILURE(status) || !getTimeZone().useDaylightTime()) michael@0: return FALSE; michael@0: michael@0: // Force an update of the state of the Calendar. michael@0: ((ChineseCalendar*)this)->complete(status); // cast away const michael@0: michael@0: return (UBool)(U_SUCCESS(status) ? (internalGet(UCAL_DST_OFFSET) != 0) : FALSE); michael@0: } michael@0: michael@0: // default century michael@0: michael@0: static UDate gSystemDefaultCenturyStart = DBL_MIN; michael@0: static int32_t gSystemDefaultCenturyStartYear = -1; michael@0: static icu::UInitOnce gSystemDefaultCenturyInitOnce = U_INITONCE_INITIALIZER; michael@0: michael@0: michael@0: UBool ChineseCalendar::haveDefaultCentury() const michael@0: { michael@0: return TRUE; michael@0: } michael@0: michael@0: UDate ChineseCalendar::defaultCenturyStart() const michael@0: { michael@0: return internalGetDefaultCenturyStart(); michael@0: } michael@0: michael@0: int32_t ChineseCalendar::defaultCenturyStartYear() const michael@0: { michael@0: return internalGetDefaultCenturyStartYear(); michael@0: } michael@0: michael@0: static void U_CALLCONV initializeSystemDefaultCentury() michael@0: { michael@0: // initialize systemDefaultCentury and systemDefaultCenturyYear based michael@0: // on the current time. They'll be set to 80 years before michael@0: // the current time. michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: ChineseCalendar calendar(Locale("@calendar=chinese"),status); michael@0: if (U_SUCCESS(status)) { michael@0: calendar.setTime(Calendar::getNow(), status); michael@0: calendar.add(UCAL_YEAR, -80, status); michael@0: gSystemDefaultCenturyStart = calendar.getTime(status); michael@0: gSystemDefaultCenturyStartYear = calendar.get(UCAL_YEAR, status); michael@0: } michael@0: // We have no recourse upon failure unless we want to propagate the failure michael@0: // out. michael@0: } michael@0: michael@0: UDate michael@0: ChineseCalendar::internalGetDefaultCenturyStart() const michael@0: { michael@0: // lazy-evaluate systemDefaultCenturyStart michael@0: umtx_initOnce(gSystemDefaultCenturyInitOnce, &initializeSystemDefaultCentury); michael@0: return gSystemDefaultCenturyStart; michael@0: } michael@0: michael@0: int32_t michael@0: ChineseCalendar::internalGetDefaultCenturyStartYear() const michael@0: { michael@0: // lazy-evaluate systemDefaultCenturyStartYear michael@0: umtx_initOnce(gSystemDefaultCenturyInitOnce, &initializeSystemDefaultCentury); michael@0: return gSystemDefaultCenturyStartYear; michael@0: } michael@0: michael@0: UOBJECT_DEFINE_RTTI_IMPLEMENTATION(ChineseCalendar) michael@0: michael@0: U_NAMESPACE_END michael@0: michael@0: #endif michael@0: