• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 ******************************************************************************
3 * Copyright (C) 2003-2006, International Business Machines Corporation
4 * and others. All Rights Reserved.
5 ******************************************************************************
6 *
7 * File ISLAMCAL.H
8 *
9 * Modification History:
10 *
11 *   Date        Name        Description
12 *   10/14/2003  srl         ported from java IslamicCalendar
13 *****************************************************************************
14 */
15 
16 #include "islamcal.h"
17 
18 #if !UCONFIG_NO_FORMATTING
19 
20 #include "umutex.h"
21 #include <float.h>
22 #include "gregoimp.h" // Math
23 #include "astro.h" // CalendarAstronomer
24 #include "uhash.h"
25 #include "ucln_in.h"
26 
27 static const UDate HIJRA_MILLIS = -42521587200000.0;    // 7/16/622 AD 00:00
28 
29 // Debugging
30 #ifdef U_DEBUG_ISLAMCAL
31 # include <stdio.h>
32 # include <stdarg.h>
debug_islamcal_loc(const char * f,int32_t l)33 static void debug_islamcal_loc(const char *f, int32_t l)
34 {
35     fprintf(stderr, "%s:%d: ", f, l);
36 }
37 
debug_islamcal_msg(const char * pat,...)38 static void debug_islamcal_msg(const char *pat, ...)
39 {
40     va_list ap;
41     va_start(ap, pat);
42     vfprintf(stderr, pat, ap);
43     fflush(stderr);
44 }
45 // must use double parens, i.e.:  U_DEBUG_ISLAMCAL_MSG(("four is: %d",4));
46 #define U_DEBUG_ISLAMCAL_MSG(x) {debug_islamcal_loc(__FILE__,__LINE__);debug_islamcal_msg x;}
47 #else
48 #define U_DEBUG_ISLAMCAL_MSG(x)
49 #endif
50 
51 
52 // --- The cache --
53 // cache of months
54 static UMTX astroLock = 0;  // pod bay door lock
55 static U_NAMESPACE_QUALIFIER CalendarCache *gMonthCache = NULL;
56 static U_NAMESPACE_QUALIFIER CalendarAstronomer *gIslamicCalendarAstro = NULL;
57 
58 U_CDECL_BEGIN
calendar_islamic_cleanup(void)59 static UBool calendar_islamic_cleanup(void) {
60     if (gMonthCache) {
61         delete gMonthCache;
62         gMonthCache = NULL;
63     }
64     if (gIslamicCalendarAstro) {
65         delete gIslamicCalendarAstro;
66         gIslamicCalendarAstro = NULL;
67     }
68     umtx_destroy(&astroLock);
69     return TRUE;
70 }
71 U_CDECL_END
72 
73 U_NAMESPACE_BEGIN
74 
75 // Implementation of the IslamicCalendar class
76 
77 //-------------------------------------------------------------------------
78 // Constructors...
79 //-------------------------------------------------------------------------
80 
getType() const81 const char *IslamicCalendar::getType() const {
82     if(civil==CIVIL) {
83         return "islamic-civil";
84     } else {
85         return "islamic";
86     }
87 }
88 
clone() const89 Calendar* IslamicCalendar::clone() const {
90     return new IslamicCalendar(*this);
91 }
92 
IslamicCalendar(const Locale & aLocale,UErrorCode & success,ECivil beCivil)93 IslamicCalendar::IslamicCalendar(const Locale& aLocale, UErrorCode& success, ECivil beCivil)
94 :   Calendar(TimeZone::createDefault(), aLocale, success),
95 civil(beCivil)
96 {
97     setTimeInMillis(getNow(), success); // Call this again now that the vtable is set up properly.
98 }
99 
IslamicCalendar(const IslamicCalendar & other)100 IslamicCalendar::IslamicCalendar(const IslamicCalendar& other) : Calendar(other), civil(other.civil) {
101 }
102 
~IslamicCalendar()103 IslamicCalendar::~IslamicCalendar()
104 {
105 }
106 
107 /**
108 * Determines whether this object uses the fixed-cycle Islamic civil calendar
109 * or an approximation of the religious, astronomical calendar.
110 *
111 * @param beCivil   <code>true</code> to use the civil calendar,
112 *                  <code>false</code> to use the astronomical calendar.
113 * @draft ICU 2.4
114 */
setCivil(ECivil beCivil,UErrorCode & status)115 void IslamicCalendar::setCivil(ECivil beCivil, UErrorCode &status)
116 {
117     if (civil != beCivil) {
118         // The fields of the calendar will become invalid, because the calendar
119         // rules are different
120         UDate m = getTimeInMillis(status);
121         civil = beCivil;
122         clear();
123         setTimeInMillis(m, status);
124     }
125 }
126 
127 /**
128 * Returns <code>true</code> if this object is using the fixed-cycle civil
129 * calendar, or <code>false</code> if using the religious, astronomical
130 * calendar.
131 * @draft ICU 2.4
132 */
isCivil()133 UBool IslamicCalendar::isCivil() {
134     return (civil == CIVIL);
135 }
136 
137 //-------------------------------------------------------------------------
138 // Minimum / Maximum access functions
139 //-------------------------------------------------------------------------
140 
141 static const int32_t LIMITS[UCAL_FIELD_COUNT][4] = {
142     // Minimum  Greatest    Least  Maximum
143     //           Minimum  Maximum
144     {        0,        0,       0,       0 }, // ERA
145     {        1,        1, 5000000, 5000000 }, // YEAR
146     {        0,        0,      11,      11 }, // MONTH
147     {        1,        1,      50,      51 }, // WEEK_OF_YEAR
148     {        0,        0,       4,       6 }, // WEEK_OF_MONTH
149     {        1,        1,      29,      30 }, // DAY_OF_MONTH
150     {        1,        1,     354,     355 }, // DAY_OF_YEAR
151     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK
152     {       -1,       -1,       5,       5 }, // DAY_OF_WEEK_IN_MONTH
153     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM
154     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR
155     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY
156     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE
157     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND
158     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND
159     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET
160     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET
161     { 1, 1, 5000001, 5000001 }, // YEAR_WOY
162     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL
163     { 1, 1, 5000000, 5000000 }, // EXTENDED_YEAR
164     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY
165     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1} // MILLISECONDS_IN_DAY
166 };
167 
168 /**
169 * @draft ICU 2.4
170 */
handleGetLimit(UCalendarDateFields field,ELimitType limitType) const171 int32_t IslamicCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const {
172     return LIMITS[field][limitType];
173 }
174 
175 //-------------------------------------------------------------------------
176 // Assorted calculation utilities
177 //
178 
179 /**
180 * Determine whether a year is a leap year in the Islamic civil calendar
181 */
civilLeapYear(int32_t year)182 UBool IslamicCalendar::civilLeapYear(int32_t year)
183 {
184     return (14 + 11 * year) % 30 < 11;
185 }
186 
187 /**
188 * Return the day # on which the given year starts.  Days are counted
189 * from the Hijri epoch, origin 0.
190 */
yearStart(int32_t year)191 int32_t IslamicCalendar::yearStart(int32_t year) {
192     if (civil == CIVIL) {
193         return (year-1)*354 + Math::floorDivide((3+11*year),30);
194     } else {
195         return trueMonthStart(12*(year-1));
196     }
197 }
198 
199 /**
200 * Return the day # on which the given month starts.  Days are counted
201 * from the Hijri epoch, origin 0.
202 *
203 * @param year  The hijri year
204 * @param year  The hijri month, 0-based
205 */
monthStart(int32_t year,int32_t month) const206 int32_t IslamicCalendar::monthStart(int32_t year, int32_t month) const {
207     if (civil == CIVIL) {
208         return (int32_t)uprv_ceil(29.5*month)
209             + (year-1)*354 + (int32_t)Math::floorDivide((3+11*year),30);
210     } else {
211         return trueMonthStart(12*(year-1) + month);
212     }
213 }
214 
215 /**
216 * Find the day number on which a particular month of the true/lunar
217 * Islamic calendar starts.
218 *
219 * @param month The month in question, origin 0 from the Hijri epoch
220 *
221 * @return The day number on which the given month starts.
222 */
trueMonthStart(int32_t month) const223 int32_t IslamicCalendar::trueMonthStart(int32_t month) const
224 {
225     UErrorCode status = U_ZERO_ERROR;
226     int32_t start = CalendarCache::get(&gMonthCache, month, status);
227 
228     if (start==0) {
229         // Make a guess at when the month started, using the average length
230         UDate origin = HIJRA_MILLIS
231             + uprv_floor(month * CalendarAstronomer::SYNODIC_MONTH - 1) * kOneDay;
232 
233         double age = moonAge(origin);
234 
235         if (moonAge(origin) >= 0) {
236             // The month has already started
237             do {
238                 origin -= kOneDay;
239                 age = moonAge(origin);
240             } while (age >= 0);
241         }
242         else {
243             // Preceding month has not ended yet.
244             do {
245                 origin += kOneDay;
246                 age = moonAge(origin);
247             } while (age < 0);
248         }
249         start = (int32_t)Math::floorDivide((origin - HIJRA_MILLIS), (double)kOneDay) + 1;
250         CalendarCache::put(&gMonthCache, month, start, status);
251     }
252     if(U_FAILURE(status)) {
253         start = 0;
254     }
255     return start;
256 }
257 
258 /**
259 * Return the "age" of the moon at the given time; this is the difference
260 * in ecliptic latitude between the moon and the sun.  This method simply
261 * calls CalendarAstronomer.moonAge, converts to degrees,
262 * and adjusts the result to be in the range [-180, 180].
263 *
264 * @param time  The time at which the moon's age is desired,
265 *              in millis since 1/1/1970.
266 */
moonAge(UDate time)267 double IslamicCalendar::moonAge(UDate time)
268 {
269     double age = 0;
270 
271     umtx_lock(&astroLock);
272     if(gIslamicCalendarAstro == NULL) {
273         gIslamicCalendarAstro = new CalendarAstronomer();
274     }
275     gIslamicCalendarAstro->setTime(time);
276     age = gIslamicCalendarAstro->getMoonAge();
277     ucln_i18n_registerCleanup(UCLN_I18N_ISLAMIC_CALENDAR, calendar_islamic_cleanup);
278     umtx_unlock(&astroLock);
279 
280     // Convert to degrees and normalize...
281     age = age * 180 / CalendarAstronomer::PI;
282     if (age > 180) {
283         age = age - 360;
284     }
285 
286     return age;
287 }
288 
289 //----------------------------------------------------------------------
290 // Calendar framework
291 //----------------------------------------------------------------------
292 
293 /**
294 * Return the length (in days) of the given month.
295 *
296 * @param year  The hijri year
297 * @param year  The hijri month, 0-based
298 * @draft ICU 2.4
299 */
handleGetMonthLength(int32_t extendedYear,int32_t month) const300 int32_t IslamicCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month) const {
301 
302     int32_t length = 0;
303 
304     if (civil == CIVIL) {
305         length = 29 + (month+1) % 2;
306         if (month == DHU_AL_HIJJAH && civilLeapYear(extendedYear)) {
307             length++;
308         }
309     } else {
310         month = 12*(extendedYear-1) + month;
311         length =  trueMonthStart(month+1) - trueMonthStart(month) ;
312     }
313     return length;
314 }
315 
316 /**
317 * Return the number of days in the given Islamic year
318 * @draft ICU 2.4
319 */
handleGetYearLength(int32_t extendedYear) const320 int32_t IslamicCalendar::handleGetYearLength(int32_t extendedYear) const {
321     if (civil == CIVIL) {
322         return 354 + (civilLeapYear(extendedYear) ? 1 : 0);
323     } else {
324         int32_t month = 12*(extendedYear-1);
325         return (trueMonthStart(month + 12) - trueMonthStart(month));
326     }
327 }
328 
329 //-------------------------------------------------------------------------
330 // Functions for converting from field values to milliseconds....
331 //-------------------------------------------------------------------------
332 
333 // Return JD of start of given month/year
334 /**
335 * @draft ICU 2.4
336 */
handleComputeMonthStart(int32_t eyear,int32_t month,UBool) const337 int32_t IslamicCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool /* useMonth */) const {
338     return monthStart(eyear, month) + 1948439;
339 }
340 
341 //-------------------------------------------------------------------------
342 // Functions for converting from milliseconds to field values
343 //-------------------------------------------------------------------------
344 
345 /**
346 * @draft ICU 2.4
347 */
handleGetExtendedYear()348 int32_t IslamicCalendar::handleGetExtendedYear() {
349     int32_t year;
350     if (newerField(UCAL_EXTENDED_YEAR, UCAL_YEAR) == UCAL_EXTENDED_YEAR) {
351         year = internalGet(UCAL_EXTENDED_YEAR, 1); // Default to year 1
352     } else {
353         year = internalGet(UCAL_YEAR, 1); // Default to year 1
354     }
355     return year;
356 }
357 
358 /**
359 * Override Calendar to compute several fields specific to the Islamic
360 * calendar system.  These are:
361 *
362 * <ul><li>ERA
363 * <li>YEAR
364 * <li>MONTH
365 * <li>DAY_OF_MONTH
366 * <li>DAY_OF_YEAR
367 * <li>EXTENDED_YEAR</ul>
368 *
369 * The DAY_OF_WEEK and DOW_LOCAL fields are already set when this
370 * method is called. The getGregorianXxx() methods return Gregorian
371 * calendar equivalents for the given Julian day.
372 * @draft ICU 2.4
373 */
handleComputeFields(int32_t julianDay,UErrorCode &)374 void IslamicCalendar::handleComputeFields(int32_t julianDay, UErrorCode &/*status*/) {
375     int32_t year, month, dayOfMonth, dayOfYear;
376     UDate startDate;
377     int32_t days = julianDay - 1948440;
378 
379     if (civil == CIVIL) {
380         // Use the civil calendar approximation, which is just arithmetic
381         year  = (int)Math::floorDivide( (double)(30 * days + 10646) , 10631.0 );
382         month = (int32_t)uprv_ceil((days - 29 - yearStart(year)) / 29.5 );
383         month = month<11?month:11;
384         startDate = monthStart(year, month);
385     } else {
386         // Guess at the number of elapsed full months since the epoch
387         int32_t months = (int32_t)uprv_floor((double)days / CalendarAstronomer::SYNODIC_MONTH);
388 
389         startDate = uprv_floor(months * CalendarAstronomer::SYNODIC_MONTH - 1);
390 
391         if ( days - startDate >= 28 && moonAge(internalGetTime()) > 0) {
392             // If we're near the end of the month, assume next month and search backwards
393             months++;
394         }
395 
396         // Find out the last time that the new moon was actually visible at this longitude
397         // This returns midnight the night that the moon was visible at sunset.
398         while ((startDate = trueMonthStart(months)) > days) {
399             // If it was after the date in question, back up a month and try again
400             months--;
401         }
402 
403         year = months / 12 + 1;
404         month = months % 12;
405     }
406 
407     dayOfMonth = (days - monthStart(year, month)) + 1;
408 
409     // Now figure out the day of the year.
410     dayOfYear = (days - monthStart(year, 0) + 1);
411 
412     internalSet(UCAL_ERA, 0);
413     internalSet(UCAL_YEAR, year);
414     internalSet(UCAL_EXTENDED_YEAR, year);
415     internalSet(UCAL_MONTH, month);
416     internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);
417     internalSet(UCAL_DAY_OF_YEAR, dayOfYear);
418 }
419 
420 UBool
inDaylightTime(UErrorCode & status) const421 IslamicCalendar::inDaylightTime(UErrorCode& status) const
422 {
423     // copied from GregorianCalendar
424     if (U_FAILURE(status) || !getTimeZone().useDaylightTime())
425         return FALSE;
426 
427     // Force an update of the state of the Calendar.
428     ((IslamicCalendar*)this)->complete(status); // cast away const
429 
430     return (UBool)(U_SUCCESS(status) ? (internalGet(UCAL_DST_OFFSET) != 0) : FALSE);
431 }
432 
433 // default century
434 const UDate     IslamicCalendar::fgSystemDefaultCentury        = DBL_MIN;
435 const int32_t   IslamicCalendar::fgSystemDefaultCenturyYear    = -1;
436 
437 UDate           IslamicCalendar::fgSystemDefaultCenturyStart       = DBL_MIN;
438 int32_t         IslamicCalendar::fgSystemDefaultCenturyStartYear   = -1;
439 
440 
haveDefaultCentury() const441 UBool IslamicCalendar::haveDefaultCentury() const
442 {
443     return TRUE;
444 }
445 
defaultCenturyStart() const446 UDate IslamicCalendar::defaultCenturyStart() const
447 {
448     return internalGetDefaultCenturyStart();
449 }
450 
defaultCenturyStartYear() const451 int32_t IslamicCalendar::defaultCenturyStartYear() const
452 {
453     return internalGetDefaultCenturyStartYear();
454 }
455 
456 UDate
internalGetDefaultCenturyStart() const457 IslamicCalendar::internalGetDefaultCenturyStart() const
458 {
459     // lazy-evaluate systemDefaultCenturyStart
460     UBool needsUpdate;
461     UMTX_CHECK(NULL, (fgSystemDefaultCenturyStart == fgSystemDefaultCentury), needsUpdate);
462 
463     if (needsUpdate) {
464         initializeSystemDefaultCentury();
465     }
466 
467     // use defaultCenturyStart unless it's the flag value;
468     // then use systemDefaultCenturyStart
469 
470     return fgSystemDefaultCenturyStart;
471 }
472 
473 int32_t
internalGetDefaultCenturyStartYear() const474 IslamicCalendar::internalGetDefaultCenturyStartYear() const
475 {
476     // lazy-evaluate systemDefaultCenturyStartYear
477     UBool needsUpdate;
478     UMTX_CHECK(NULL, (fgSystemDefaultCenturyStart == fgSystemDefaultCentury), needsUpdate);
479 
480     if (needsUpdate) {
481         initializeSystemDefaultCentury();
482     }
483 
484     // use defaultCenturyStart unless it's the flag value;
485     // then use systemDefaultCenturyStartYear
486 
487     return    fgSystemDefaultCenturyStartYear;
488 }
489 
490 void
initializeSystemDefaultCentury()491 IslamicCalendar::initializeSystemDefaultCentury()
492 {
493     // initialize systemDefaultCentury and systemDefaultCenturyYear based
494     // on the current time.  They'll be set to 80 years before
495     // the current time.
496     // No point in locking as it should be idempotent.
497     if (fgSystemDefaultCenturyStart == fgSystemDefaultCentury)
498     {
499         UErrorCode status = U_ZERO_ERROR;
500         IslamicCalendar calendar(Locale("@calendar=islamic-civil"),status);
501         if (U_SUCCESS(status))
502         {
503             calendar.setTime(Calendar::getNow(), status);
504             calendar.add(UCAL_YEAR, -80, status);
505             UDate    newStart =  calendar.getTime(status);
506             int32_t  newYear  =  calendar.get(UCAL_YEAR, status);
507             {
508                 umtx_lock(NULL);
509                 fgSystemDefaultCenturyStart = newStart;
510                 fgSystemDefaultCenturyStartYear = newYear;
511                 umtx_unlock(NULL);
512             }
513         }
514         // We have no recourse upon failure unless we want to propagate the failure
515         // out.
516     }
517 }
518 
519 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(IslamicCalendar)
520 
521 U_NAMESPACE_END
522 
523 #endif
524 
525