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