1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 ******************************************************************************
5 * Copyright (C) 2003-2016, International Business Machines Corporation
6 * and others. All Rights Reserved.
7 ******************************************************************************
8 *
9 * File HEBRWCAL.CPP
10 *
11 * Modification History:
12 *
13 * Date Name Description
14 * 12/03/2003 srl ported from java HebrewCalendar
15 *****************************************************************************
16 */
17
18 #include "hebrwcal.h"
19
20 #if !UCONFIG_NO_FORMATTING
21
22 #include "cmemory.h"
23 #include "cstring.h"
24 #include "umutex.h"
25 #include <float.h>
26 #include "gregoimp.h" // ClockMath
27 #include "astro.h" // CalendarCache
28 #include "uhash.h"
29 #include "ucln_in.h"
30
31 // Hebrew Calendar implementation
32
33 /**
34 * The absolute date, in milliseconds since 1/1/1970 AD, Gregorian,
35 * of the start of the Hebrew calendar. In order to keep this calendar's
36 * time of day in sync with that of the Gregorian calendar, we use
37 * midnight, rather than sunset the day before.
38 */
39 //static const double EPOCH_MILLIS = -180799862400000.; // 1/1/1 HY
40
41 static const int32_t LIMITS[UCAL_FIELD_COUNT][4] = {
42 // Minimum Greatest Least Maximum
43 // Minimum Maximum
44 { 0, 0, 0, 0}, // ERA
45 { -5000000, -5000000, 5000000, 5000000}, // YEAR
46 { 0, 0, 12, 12}, // MONTH
47 { 1, 1, 51, 56}, // WEEK_OF_YEAR
48 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // WEEK_OF_MONTH
49 { 1, 1, 29, 30}, // DAY_OF_MONTH
50 { 1, 1, 353, 385}, // DAY_OF_YEAR
51 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK
52 { -1, -1, 5, 5}, // DAY_OF_WEEK_IN_MONTH
53 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM
54 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR
55 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY
56 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE
57 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND
58 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND
59 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET
60 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET
61 { -5000000, -5000000, 5000000, 5000000}, // YEAR_WOY
62 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL
63 { -5000000, -5000000, 5000000, 5000000}, // EXTENDED_YEAR
64 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY
65 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECONDS_IN_DAY
66 {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // IS_LEAP_MONTH
67 { 0, 0, 11, 12}, // ORDINAL_MONTH
68 };
69
70 /**
71 * The lengths of the Hebrew months. This is complicated, because there
72 * are three different types of years, or six if you count leap years.
73 * Due to the rules for postponing the start of the year to avoid having
74 * certain holidays fall on the sabbath, the year can end up being three
75 * different lengths, called "deficient", "normal", and "complete".
76 */
77 static const int8_t MONTH_LENGTH[][3] = {
78 // Deficient Normal Complete
79 { 30, 30, 30 }, //Tishri
80 { 29, 29, 30 }, //Heshvan
81 { 29, 30, 30 }, //Kislev
82 { 29, 29, 29 }, //Tevet
83 { 30, 30, 30 }, //Shevat
84 { 30, 30, 30 }, //Adar I (leap years only)
85 { 29, 29, 29 }, //Adar
86 { 30, 30, 30 }, //Nisan
87 { 29, 29, 29 }, //Iyar
88 { 30, 30, 30 }, //Sivan
89 { 29, 29, 29 }, //Tammuz
90 { 30, 30, 30 }, //Av
91 { 29, 29, 29 }, //Elul
92 };
93
94 /**
95 * The cumulative # of days to the end of each month in a non-leap year
96 * Although this can be calculated from the MONTH_LENGTH table,
97 * keeping it around separately makes some calculations a lot faster
98 */
99
100 static const int16_t MONTH_START[][3] = {
101 // Deficient Normal Complete
102 { 0, 0, 0 }, // (placeholder)
103 { 30, 30, 30 }, // Tishri
104 { 59, 59, 60 }, // Heshvan
105 { 88, 89, 90 }, // Kislev
106 { 117, 118, 119 }, // Tevet
107 { 147, 148, 149 }, // Shevat
108 { 147, 148, 149 }, // (Adar I placeholder)
109 { 176, 177, 178 }, // Adar
110 { 206, 207, 208 }, // Nisan
111 { 235, 236, 237 }, // Iyar
112 { 265, 266, 267 }, // Sivan
113 { 294, 295, 296 }, // Tammuz
114 { 324, 325, 326 }, // Av
115 { 353, 354, 355 }, // Elul
116 };
117
118 /**
119 * The cumulative # of days to the end of each month in a leap year
120 */
121 static const int16_t LEAP_MONTH_START[][3] = {
122 // Deficient Normal Complete
123 { 0, 0, 0 }, // (placeholder)
124 { 30, 30, 30 }, // Tishri
125 { 59, 59, 60 }, // Heshvan
126 { 88, 89, 90 }, // Kislev
127 { 117, 118, 119 }, // Tevet
128 { 147, 148, 149 }, // Shevat
129 { 177, 178, 179 }, // Adar I
130 { 206, 207, 208 }, // Adar II
131 { 236, 237, 238 }, // Nisan
132 { 265, 266, 267 }, // Iyar
133 { 295, 296, 297 }, // Sivan
134 { 324, 325, 326 }, // Tammuz
135 { 354, 355, 356 }, // Av
136 { 383, 384, 385 }, // Elul
137 };
138
139 // There are 235 months in 19 years cycle.
140 static const int32_t MONTHS_IN_CYCLE = 235;
141 static const int32_t YEARS_IN_CYCLE = 19;
142
143 static icu::CalendarCache *gCache = nullptr;
144
145 U_CDECL_BEGIN
calendar_hebrew_cleanup()146 static UBool calendar_hebrew_cleanup() {
147 delete gCache;
148 gCache = nullptr;
149 return true;
150 }
151 U_CDECL_END
152
153 U_NAMESPACE_BEGIN
154 //-------------------------------------------------------------------------
155 // Constructors...
156 //-------------------------------------------------------------------------
157
158 /**
159 * Constructs a default <code>HebrewCalendar</code> using the current time
160 * in the default time zone with the default locale.
161 * @internal
162 */
HebrewCalendar(const Locale & aLocale,UErrorCode & success)163 HebrewCalendar::HebrewCalendar(const Locale& aLocale, UErrorCode& success)
164 : Calendar(TimeZone::forLocaleOrDefault(aLocale), aLocale, success)
165
166 {
167 setTimeInMillis(getNow(), success); // Call this again now that the vtable is set up properly.
168 }
169
170
~HebrewCalendar()171 HebrewCalendar::~HebrewCalendar() {
172 }
173
getType() const174 const char *HebrewCalendar::getType() const {
175 return "hebrew";
176 }
177
clone() const178 HebrewCalendar* HebrewCalendar::clone() const {
179 return new HebrewCalendar(*this);
180 }
181
HebrewCalendar(const HebrewCalendar & other)182 HebrewCalendar::HebrewCalendar(const HebrewCalendar& other) : Calendar(other) {
183 }
184
185
186 //-------------------------------------------------------------------------
187 // Rolling and adding functions overridden from Calendar
188 //
189 // These methods call through to the default implementation in IBMCalendar
190 // for most of the fields and only handle the unusual ones themselves.
191 //-------------------------------------------------------------------------
192
193 /**
194 * Add a signed amount to a specified field, using this calendar's rules.
195 * For example, to add three days to the current date, you can call
196 * <code>add(Calendar.DATE, 3)</code>.
197 * <p>
198 * When adding to certain fields, the values of other fields may conflict and
199 * need to be changed. For example, when adding one to the {@link #MONTH MONTH} field
200 * for the date "30 Av 5758", the {@link #DAY_OF_MONTH DAY_OF_MONTH} field
201 * must be adjusted so that the result is "29 Elul 5758" rather than the invalid
202 * "30 Elul 5758".
203 * <p>
204 * This method is able to add to
205 * all fields except for {@link #ERA ERA}, {@link #DST_OFFSET DST_OFFSET},
206 * and {@link #ZONE_OFFSET ZONE_OFFSET}.
207 * <p>
208 * <b>Note:</b> You should always use {@link #roll roll} and add rather
209 * than attempting to perform arithmetic operations directly on the fields
210 * of a <tt>HebrewCalendar</tt>. Since the {@link #MONTH MONTH} field behaves
211 * discontinuously in non-leap years, simple arithmetic can give invalid results.
212 * <p>
213 * @param field the time field.
214 * @param amount the amount to add to the field.
215 *
216 * @exception IllegalArgumentException if the field is invalid or refers
217 * to a field that cannot be handled by this method.
218 * @internal
219 */
add(UCalendarDateFields field,int32_t amount,UErrorCode & status)220 void HebrewCalendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& status)
221 {
222 if(U_FAILURE(status)) {
223 return;
224 }
225 switch (field) {
226 case UCAL_MONTH:
227 case UCAL_ORDINAL_MONTH:
228 {
229 // We can't just do a set(MONTH, get(MONTH) + amount). The
230 // reason is ADAR_1. Suppose amount is +2 and we land in
231 // ADAR_1 -- then we have to bump to ADAR_2 aka ADAR. But
232 // if amount is -2 and we land in ADAR_1, then we have to
233 // bump the other way -- down to SHEVAT. - Alan 11/00
234 int64_t month = get(UCAL_MONTH, status);
235 int32_t year = get(UCAL_YEAR, status);
236 UBool acrossAdar1;
237 if (amount > 0) {
238 acrossAdar1 = (month < ADAR_1); // started before ADAR_1?
239 month += amount;
240 // We know there are total 235 months in every 19 years. To speed
241 // up the iteration, we first fast forward in the multiple of 235
242 // months for 19 years before the iteration which check the leap year.
243 if (month >= MONTHS_IN_CYCLE) {
244 if (uprv_add32_overflow(year, (month / MONTHS_IN_CYCLE) * YEARS_IN_CYCLE, &year)) {
245 status = U_ILLEGAL_ARGUMENT_ERROR;
246 return;
247 }
248 month %= MONTHS_IN_CYCLE;
249 }
250
251 for (;;) {
252 if (acrossAdar1 && month>=ADAR_1 && !isLeapYear(year)) {
253 ++month;
254 }
255 if (month <= ELUL) {
256 break;
257 }
258 month -= ELUL+1;
259 ++year;
260 acrossAdar1 = true;
261 }
262 } else {
263 acrossAdar1 = (month > ADAR_1); // started after ADAR_1?
264 month += amount;
265 // We know there are total 235 months in every 19 years. To speed
266 // up the iteration, we first fast forward in the multiple of 235
267 // months for 19 years before the iteration which check the leap year.
268 if (month <= -MONTHS_IN_CYCLE) {
269 if (uprv_add32_overflow(year, (month / MONTHS_IN_CYCLE) * YEARS_IN_CYCLE, &year)) {
270 status = U_ILLEGAL_ARGUMENT_ERROR;
271 return;
272 }
273 month %= MONTHS_IN_CYCLE;
274 }
275 for (;;) {
276 if (acrossAdar1 && month<=ADAR_1 && !isLeapYear(year)) {
277 --month;
278 }
279 if (month >= 0) {
280 break;
281 }
282 month += ELUL+1;
283 --year;
284 acrossAdar1 = true;
285 }
286 }
287 set(UCAL_MONTH, month);
288 set(UCAL_YEAR, year);
289 pinField(UCAL_DAY_OF_MONTH, status);
290 break;
291 }
292
293 default:
294 Calendar::add(field, amount, status);
295 break;
296 }
297 }
298
299 /**
300 * @deprecated ICU 2.6 use UCalendarDateFields instead of EDateFields
301 */
add(EDateFields field,int32_t amount,UErrorCode & status)302 void HebrewCalendar::add(EDateFields field, int32_t amount, UErrorCode& status)
303 {
304 add((UCalendarDateFields)field, amount, status);
305 }
306
307 /**
308 * Rolls (up/down) a specified amount time on the given field. For
309 * example, to roll the current date up by three days, you can call
310 * <code>roll(Calendar.DATE, 3)</code>. If the
311 * field is rolled past its maximum allowable value, it will "wrap" back
312 * to its minimum and continue rolling.
313 * For example, calling <code>roll(Calendar.DATE, 10)</code>
314 * on a Hebrew calendar set to "25 Av 5758" will result in the date "5 Av 5758".
315 * <p>
316 * When rolling certain fields, the values of other fields may conflict and
317 * need to be changed. For example, when rolling the {@link #MONTH MONTH} field
318 * upward by one for the date "30 Av 5758", the {@link #DAY_OF_MONTH DAY_OF_MONTH} field
319 * must be adjusted so that the result is "29 Elul 5758" rather than the invalid
320 * "30 Elul".
321 * <p>
322 * This method is able to roll
323 * all fields except for {@link #ERA ERA}, {@link #DST_OFFSET DST_OFFSET},
324 * and {@link #ZONE_OFFSET ZONE_OFFSET}. Subclasses may, of course, add support for
325 * additional fields in their overrides of <code>roll</code>.
326 * <p>
327 * <b>Note:</b> You should always use roll and {@link #add add} rather
328 * than attempting to perform arithmetic operations directly on the fields
329 * of a <tt>HebrewCalendar</tt>. Since the {@link #MONTH MONTH} field behaves
330 * discontinuously in non-leap years, simple arithmetic can give invalid results.
331 * <p>
332 * @param field the time field.
333 * @param amount the amount by which the field should be rolled.
334 *
335 * @exception IllegalArgumentException if the field is invalid or refers
336 * to a field that cannot be handled by this method.
337 * @internal
338 */
roll(UCalendarDateFields field,int32_t amount,UErrorCode & status)339 void HebrewCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status)
340 {
341 if(U_FAILURE(status)) {
342 return;
343 }
344 switch (field) {
345 case UCAL_MONTH:
346 case UCAL_ORDINAL_MONTH:
347 {
348 int32_t month = get(UCAL_MONTH, status);
349 int32_t year = get(UCAL_YEAR, status);
350
351 UBool leapYear = isLeapYear(year);
352 int32_t yearLength = monthsInYear(year);
353 int32_t newMonth = month + (amount % yearLength);
354 //
355 // If it's not a leap year and we're rolling past the missing month
356 // of ADAR_1, we need to roll an extra month to make up for it.
357 //
358 if (!leapYear) {
359 if (amount > 0 && month < ADAR_1 && newMonth >= ADAR_1) {
360 newMonth++;
361 } else if (amount < 0 && month > ADAR_1 && newMonth <= ADAR_1) {
362 newMonth--;
363 }
364 }
365 set(UCAL_MONTH, (newMonth + 13) % 13);
366 pinField(UCAL_DAY_OF_MONTH, status);
367 return;
368 }
369 default:
370 Calendar::roll(field, amount, status);
371 }
372 }
373
roll(EDateFields field,int32_t amount,UErrorCode & status)374 void HebrewCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) {
375 roll((UCalendarDateFields)field, amount, status);
376 }
377
378 //-------------------------------------------------------------------------
379 // Support methods
380 //-------------------------------------------------------------------------
381
382 // Hebrew date calculations are performed in terms of days, hours, and
383 // "parts" (or halakim), which are 1/1080 of an hour, or 3 1/3 seconds.
384 static const int32_t HOUR_PARTS = 1080;
385 static const int32_t DAY_PARTS = 24*HOUR_PARTS;
386
387 // An approximate value for the length of a lunar month.
388 // It is used to calculate the approximate year and month of a given
389 // absolute date.
390 static const int32_t MONTH_DAYS = 29;
391 static const int32_t MONTH_FRACT = 12*HOUR_PARTS + 793;
392 static const int32_t MONTH_PARTS = MONTH_DAYS*DAY_PARTS + MONTH_FRACT;
393
394 // The time of the new moon (in parts) on 1 Tishri, year 1 (the epoch)
395 // counting from noon on the day before. BAHARAD is an abbreviation of
396 // Bet (Monday), Hey (5 hours from sunset), Resh-Daled (204).
397 static const int32_t BAHARAD = 11*HOUR_PARTS + 204;
398
399 /**
400 * Finds the day # of the first day in the given Hebrew year.
401 * To do this, we want to calculate the time of the Tishri 1 new moon
402 * in that year.
403 * <p>
404 * The algorithm here is similar to ones described in a number of
405 * references, including:
406 * <ul>
407 * <li>"Calendrical Calculations", by Nachum Dershowitz & Edward Reingold,
408 * Cambridge University Press, 1997, pages 85-91.
409 *
410 * <li>Hebrew Calendar Science and Myths,
411 * <a href="http://www.geocities.com/Athens/1584/">
412 * http://www.geocities.com/Athens/1584/</a>
413 *
414 * <li>The Calendar FAQ,
415 * <a href="http://www.faqs.org/faqs/calendars/faq/">
416 * http://www.faqs.org/faqs/calendars/faq/</a>
417 * </ul>
418 */
startOfYear(int32_t year,UErrorCode & status)419 int32_t HebrewCalendar::startOfYear(int32_t year, UErrorCode &status)
420 {
421 ucln_i18n_registerCleanup(UCLN_I18N_HEBREW_CALENDAR, calendar_hebrew_cleanup);
422 int64_t day = CalendarCache::get(&gCache, year, status);
423 if(U_FAILURE(status)) {
424 return 0;
425 }
426
427 if (day == 0) {
428 // # of months before year
429 int64_t months = ClockMath::floorDivideInt64(
430 (235LL * (int64_t)year - 234LL), 19LL);
431
432 int64_t frac = months * MONTH_FRACT + BAHARAD; // Fractional part of day #
433 day = months * 29LL + frac / DAY_PARTS; // Whole # part of calculation
434 frac = frac % DAY_PARTS; // Time of day
435
436 int32_t wd = (day % 7); // Day of week (0 == Monday)
437
438 if (wd == 2 || wd == 4 || wd == 6) {
439 // If the 1st is on Sun, Wed, or Fri, postpone to the next day
440 day += 1;
441 wd = (day % 7);
442 }
443 if (wd == 1 && frac > 15*HOUR_PARTS+204 && !isLeapYear(year) ) {
444 // If the new moon falls after 3:11:20am (15h204p from the previous noon)
445 // on a Tuesday and it is not a leap year, postpone by 2 days.
446 // This prevents 356-day years.
447 day += 2;
448 }
449 else if (wd == 0 && frac > 21*HOUR_PARTS+589 && isLeapYear(year-1) ) {
450 // If the new moon falls after 9:32:43 1/3am (21h589p from yesterday noon)
451 // on a Monday and *last* year was a leap year, postpone by 1 day.
452 // Prevents 382-day years.
453 day += 1;
454 }
455 if (day > INT32_MAX || day < INT32_MIN) {
456 status = U_ILLEGAL_ARGUMENT_ERROR;
457 return 0;
458 }
459 CalendarCache::put(&gCache, year, static_cast<int32_t>(day), status);
460 }
461 // Out of range value is alread rejected before putting into cache.
462 U_ASSERT(INT32_MIN <= day && day <= INT32_MAX);
463 return day;
464 }
465
466 /**
467 * Find the day of the week for a given day
468 *
469 * @param day The # of days since the start of the Hebrew calendar,
470 * 1-based (i.e. 1/1/1 AM is day 1).
471 */
absoluteDayToDayOfWeek(int32_t day)472 int32_t HebrewCalendar::absoluteDayToDayOfWeek(int32_t day)
473 {
474 // We know that 1/1/1 AM is a Monday, which makes the math easy...
475 return (day % 7) + 1;
476 }
477
478 /**
479 * Returns the the type of a given year.
480 * 0 "Deficient" year with 353 or 383 days
481 * 1 "Normal" year with 354 or 384 days
482 * 2 "Complete" year with 355 or 385 days
483 */
yearType(int32_t year) const484 int32_t HebrewCalendar::yearType(int32_t year) const
485 {
486 int32_t yearLength = handleGetYearLength(year);
487
488 if (yearLength > 380) {
489 yearLength -= 30; // Subtract length of leap month.
490 }
491
492 int type = 0;
493
494 switch (yearLength) {
495 case 353:
496 type = 0; break;
497 case 354:
498 type = 1; break;
499 case 355:
500 type = 2; break;
501 default:
502 //throw new RuntimeException("Illegal year length " + yearLength + " in year " + year);
503 type = 1;
504 }
505 return type;
506 }
507
508 /**
509 * Determine whether a given Hebrew year is a leap year
510 *
511 * The rule here is that if (year % 19) == 0, 3, 6, 8, 11, 14, or 17.
512 * The formula below performs the same test, believe it or not.
513 */
isLeapYear(int32_t year)514 UBool HebrewCalendar::isLeapYear(int32_t year) {
515 //return (year * 12 + 17) % 19 >= 12;
516 int64_t x = (year*12LL + 17) % YEARS_IN_CYCLE;
517 return x >= ((x < 0) ? -7 : 12);
518 }
519
monthsInYear(int32_t year)520 int32_t HebrewCalendar::monthsInYear(int32_t year) {
521 return isLeapYear(year) ? 13 : 12;
522 }
523
524 //-------------------------------------------------------------------------
525 // Calendar framework
526 //-------------------------------------------------------------------------
527
528 /**
529 * @internal
530 */
handleGetLimit(UCalendarDateFields field,ELimitType limitType) const531 int32_t HebrewCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const {
532 return LIMITS[field][limitType];
533 }
534
535 /**
536 * Returns the length of the given month in the given year
537 * @internal
538 */
handleGetMonthLength(int32_t extendedYear,int32_t month,UErrorCode & status) const539 int32_t HebrewCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month, UErrorCode& status) const {
540 if(U_FAILURE(status)) {
541 return 0;
542 }
543 // Resolve out-of-range months. This is necessary in order to
544 // obtain the correct year. We correct to
545 // a 12- or 13-month year (add/subtract 12 or 13, depending
546 // on the year) but since we _always_ number from 0..12, and
547 // the leap year determines whether or not month 5 (Adar 1)
548 // is present, we allow 0..12 in any given year.
549 while (month < 0) {
550 month += monthsInYear(--extendedYear);
551 }
552 // Careful: allow 0..12 in all years
553 while (month > 12) {
554 month -= monthsInYear(extendedYear++);
555 }
556
557 switch (month) {
558 case HESHVAN:
559 case KISLEV:
560 // These two month lengths can vary
561 return MONTH_LENGTH[month][yearType(extendedYear)];
562
563 default:
564 // The rest are a fixed length
565 return MONTH_LENGTH[month][0];
566 }
567 }
568
569 /**
570 * Returns the number of days in the given Hebrew year
571 * @internal
572 */
handleGetYearLength(int32_t eyear) const573 int32_t HebrewCalendar::handleGetYearLength(int32_t eyear) const {
574 UErrorCode status = U_ZERO_ERROR;
575 return startOfYear(eyear+1, status) - startOfYear(eyear, status);
576 }
577
validateField(UCalendarDateFields field,UErrorCode & status)578 void HebrewCalendar::validateField(UCalendarDateFields field, UErrorCode &status) {
579 if ((field == UCAL_MONTH || field == UCAL_ORDINAL_MONTH)
580 && !isLeapYear(handleGetExtendedYear(status)) && internalGetMonth(status) == ADAR_1) {
581 if (U_FAILURE(status)) {
582 return;
583 }
584 status = U_ILLEGAL_ARGUMENT_ERROR;
585 return;
586 }
587 Calendar::validateField(field, status);
588 }
589 //-------------------------------------------------------------------------
590 // Functions for converting from milliseconds to field values
591 //-------------------------------------------------------------------------
592
593 /**
594 * Subclasses may override this method to compute several fields
595 * specific to each calendar system. These are:
596 *
597 * <ul><li>ERA
598 * <li>YEAR
599 * <li>MONTH
600 * <li>DAY_OF_MONTH
601 * <li>DAY_OF_YEAR
602 * <li>EXTENDED_YEAR</ul>
603 *
604 * Subclasses can refer to the DAY_OF_WEEK and DOW_LOCAL fields,
605 * which will be set when this method is called. Subclasses can
606 * also call the getGregorianXxx() methods to obtain Gregorian
607 * calendar equivalents for the given Julian day.
608 *
609 * <p>In addition, subclasses should compute any subclass-specific
610 * fields, that is, fields from BASE_FIELD_COUNT to
611 * getFieldCount() - 1.
612 * @internal
613 */
handleComputeFields(int32_t julianDay,UErrorCode & status)614 void HebrewCalendar::handleComputeFields(int32_t julianDay, UErrorCode &status) {
615 if (U_FAILURE(status)) {
616 return;
617 }
618 int32_t d = julianDay - 347997;
619 double m = ClockMath::floorDivide((d * (double)DAY_PARTS), (double) MONTH_PARTS); // Months (approx)
620 int32_t year = (int32_t)(ClockMath::floorDivide((19. * m + 234.), 235.) + 1.); // Years (approx)
621 int32_t ys = startOfYear(year, status); // 1st day of year
622 if (U_FAILURE(status)) {
623 return;
624 }
625 int32_t dayOfYear = (d - ys);
626
627 // Because of the postponement rules, it's possible to guess wrong. Fix it.
628 while (dayOfYear < 1) {
629 year--;
630 ys = startOfYear(year, status);
631 if (U_FAILURE(status)) {
632 return;
633 }
634 dayOfYear = (d - ys);
635 }
636
637 // Now figure out which month we're in, and the date within that month
638 int32_t type = yearType(year);
639 UBool isLeap = isLeapYear(year);
640
641 int32_t month = 0;
642 int32_t momax = UPRV_LENGTHOF(MONTH_START);
643 while (month < momax && dayOfYear > ( isLeap ? LEAP_MONTH_START[month][type] : MONTH_START[month][type] ) ) {
644 month++;
645 }
646 if (month >= momax || month<=0) {
647 // TODO: I found dayOfYear could be out of range when
648 // a large value is set to julianDay. I patched startOfYear
649 // to reduce the chace, but it could be still reproduced either
650 // by startOfYear or other places. For now, we check
651 // the month is in valid range to avoid out of array index
652 // access problem here. However, we need to carefully review
653 // the calendar implementation to check the extreme limit of
654 // each calendar field and the code works well for any values
655 // in the valid value range. -yoshito
656 status = U_ILLEGAL_ARGUMENT_ERROR;
657 return;
658 }
659 month--;
660 int dayOfMonth = dayOfYear - (isLeap ? LEAP_MONTH_START[month][type] : MONTH_START[month][type]);
661
662 internalSet(UCAL_ERA, 0);
663 // Check out of bound year
664 int32_t min_year = handleGetLimit(UCAL_EXTENDED_YEAR, UCAL_LIMIT_MINIMUM);
665 if (year < min_year) {
666 if (!isLenient()) {
667 status = U_ILLEGAL_ARGUMENT_ERROR;
668 return;
669 }
670 year = min_year;
671 }
672 int32_t max_year = handleGetLimit(UCAL_EXTENDED_YEAR, UCAL_LIMIT_MAXIMUM);
673 if (max_year < year) {
674 if (!isLenient()) {
675 status = U_ILLEGAL_ARGUMENT_ERROR;
676 return;
677 }
678 year = max_year;
679 }
680 internalSet(UCAL_YEAR, year);
681 internalSet(UCAL_EXTENDED_YEAR, year);
682 int32_t ordinal_month = month;
683 if (!isLeap && ordinal_month > ADAR_1) {
684 ordinal_month--;
685 }
686 internalSet(UCAL_ORDINAL_MONTH, ordinal_month);
687 internalSet(UCAL_MONTH, month);
688 internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);
689 internalSet(UCAL_DAY_OF_YEAR, dayOfYear);
690 }
691
692 //-------------------------------------------------------------------------
693 // Functions for converting from field values to milliseconds
694 //-------------------------------------------------------------------------
695
696 /**
697 * @internal
698 */
handleGetExtendedYear(UErrorCode & status)699 int32_t HebrewCalendar::handleGetExtendedYear(UErrorCode& status ) {
700 if (U_FAILURE(status)) {
701 return 0;
702 }
703 if (newerField(UCAL_EXTENDED_YEAR, UCAL_YEAR) == UCAL_EXTENDED_YEAR) {
704 return internalGet(UCAL_EXTENDED_YEAR, 1); // Default to year 1
705 }
706 return internalGet(UCAL_YEAR, 1); // Default to year 1
707 }
708
709 /**
710 * Return JD of start of given month/year.
711 * @internal
712 */
handleComputeMonthStart(int32_t eyear,int32_t month,UBool,UErrorCode & status) const713 int64_t HebrewCalendar::handleComputeMonthStart(
714 int32_t eyear, int32_t month, UBool /*useMonth*/, UErrorCode& status) const {
715 if (U_FAILURE(status)) {
716 return 0;
717 }
718 // Resolve out-of-range months. This is necessary in order to
719 // obtain the correct year. We correct to
720 // a 12- or 13-month year (add/subtract 12 or 13, depending
721 // on the year) but since we _always_ number from 0..12, and
722 // the leap year determines whether or not month 5 (Adar 1)
723 // is present, we allow 0..12 in any given year.
724
725 // The month could be in large value, we first roll 235 months to 19 years
726 // before the while loop.
727 if (month <= -MONTHS_IN_CYCLE || month >= MONTHS_IN_CYCLE) {
728 if (uprv_add32_overflow(eyear, (month / MONTHS_IN_CYCLE) * YEARS_IN_CYCLE, &eyear)) {
729 status = U_ILLEGAL_ARGUMENT_ERROR;
730 return 0;
731 }
732 month %= MONTHS_IN_CYCLE;
733 }
734 while (month < 0) {
735 if (uprv_add32_overflow(eyear, -1, &eyear) ||
736 uprv_add32_overflow(month, monthsInYear(eyear), &month)) {
737 status = U_ILLEGAL_ARGUMENT_ERROR;
738 return 0;
739 }
740 }
741 // Careful: allow 0..12 in all years
742 while (month > 12) {
743 if (uprv_add32_overflow(month, -monthsInYear(eyear), &month) ||
744 uprv_add32_overflow(eyear, 1, &eyear)) {
745 status = U_ILLEGAL_ARGUMENT_ERROR;
746 return 0;
747 }
748 }
749
750 int64_t day = startOfYear(eyear, status);
751
752 if(U_FAILURE(status)) {
753 return 0;
754 }
755
756 if (month != 0) {
757 if (isLeapYear(eyear)) {
758 day += LEAP_MONTH_START[month][yearType(eyear)];
759 } else {
760 day += MONTH_START[month][yearType(eyear)];
761 }
762 }
763
764 return day + 347997LL;
765 }
766
767 constexpr uint32_t kHebrewRelatedYearDiff = -3760;
768
getRelatedYear(UErrorCode & status) const769 int32_t HebrewCalendar::getRelatedYear(UErrorCode &status) const
770 {
771 int32_t year = get(UCAL_EXTENDED_YEAR, status);
772 if (U_FAILURE(status)) {
773 return 0;
774 }
775 return year + kHebrewRelatedYearDiff;
776 }
777
setRelatedYear(int32_t year)778 void HebrewCalendar::setRelatedYear(int32_t year)
779 {
780 // set extended year
781 set(UCAL_EXTENDED_YEAR, year - kHebrewRelatedYearDiff);
782 }
783
784 IMPL_SYSTEM_DEFAULT_CENTURY(HebrewCalendar, "@calendar=hebrew")
785
inTemporalLeapYear(UErrorCode & status) const786 bool HebrewCalendar::inTemporalLeapYear(UErrorCode& status) const {
787 if (U_FAILURE(status)) {
788 return false;
789 }
790 int32_t eyear = get(UCAL_EXTENDED_YEAR, status);
791 if (U_FAILURE(status)) {
792 return false;
793 }
794 return isLeapYear(eyear);
795 }
796
797 static const char * const gTemporalMonthCodesForHebrew[] = {
798 "M01", "M02", "M03", "M04", "M05", "M05L", "M06",
799 "M07", "M08", "M09", "M10", "M11", "M12", nullptr
800 };
801
getTemporalMonthCode(UErrorCode & status) const802 const char* HebrewCalendar::getTemporalMonthCode(UErrorCode& status) const {
803 int32_t month = get(UCAL_MONTH, status);
804 if (U_FAILURE(status)) {
805 return nullptr;
806 }
807 return gTemporalMonthCodesForHebrew[month];
808 }
809
setTemporalMonthCode(const char * code,UErrorCode & status)810 void HebrewCalendar::setTemporalMonthCode(const char* code, UErrorCode& status )
811 {
812 if (U_FAILURE(status)) {
813 return;
814 }
815 int32_t len = static_cast<int32_t>(uprv_strlen(code));
816 if (len == 3 || len == 4) {
817 for (int m = 0; gTemporalMonthCodesForHebrew[m] != nullptr; m++) {
818 if (uprv_strcmp(code, gTemporalMonthCodesForHebrew[m]) == 0) {
819 set(UCAL_MONTH, m);
820 return;
821 }
822 }
823 }
824 status = U_ILLEGAL_ARGUMENT_ERROR;
825 }
826
internalGetMonth(UErrorCode & status) const827 int32_t HebrewCalendar::internalGetMonth(UErrorCode& status) const {
828 if (U_FAILURE(status)) {
829 return 0;
830 }
831 if (resolveFields(kMonthPrecedence) == UCAL_ORDINAL_MONTH) {
832 int32_t ordinalMonth = internalGet(UCAL_ORDINAL_MONTH);
833 HebrewCalendar *nonConstThis = (HebrewCalendar*)this; // cast away const
834
835 int32_t year = nonConstThis->handleGetExtendedYear(status);
836 if (U_FAILURE(status)) {
837 return 0;
838 }
839 if (isLeapYear(year) || ordinalMonth <= ADAR_1) {
840 return ordinalMonth;
841 }
842 if (!uprv_add32_overflow(ordinalMonth, 1, &ordinalMonth)) {
843 return ordinalMonth;
844 }
845 }
846 return Calendar::internalGetMonth(status);
847 }
848
849 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(HebrewCalendar)
850
851 U_NAMESPACE_END
852
853 #endif // UCONFIG_NO_FORMATTING
854
855