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