ICU-2424 islamic calendar

X-SVN-Rev: 13845
This commit is contained in:
Steven R. Loomis 2003-11-24 20:02:11 +00:00
parent d0fdad09c6
commit 24f0431f78
6 changed files with 3792 additions and 28 deletions

View File

@ -60,7 +60,7 @@ OBJECTS = ucln_in.o \
fmtable.o format.o msgfmt.o umsg.o numfmt.o unum.o decimfmt.o dcfmtsym.o \
choicfmt.o datefmt.o smpdtfmt.o dtfmtsym.o udat.o \
ucal.o calendar.o gregocal.o timezone.o simpletz.o olsontz.o \
buddhcal.o japancal.o gregoimp.o \
astro.o buddhcal.o islamcal.o japancal.o gregoimp.o \
sortkey.o bocsu.o coleitr.o coll.o ucoleitr.o \
ucol.o ucol_bld.o ucol_cnt.o ucol_elm.o ucol_tok.o ucol_wgt.o tblcoll.o \
strmatch.o usearch.o search.o stsearch.o \

1422
icu4c/source/i18n/astro.cpp Normal file

File diff suppressed because it is too large Load Diff

1277
icu4c/source/i18n/astro.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -33,9 +33,7 @@
#include "gregoimp.h"
#include "buddhcal.h"
#include "japancal.h"
#if defined(SRL_HAVE_ISLAMIC)
#include "islamcal.h"
#endif
#include "unicode/calendar.h"
#include "cpputils.h"
#include "iculserv.h"
@ -127,6 +125,11 @@ protected:
}
virtual UObject* create(const ICUServiceKey& key, const ICUService* /*service*/, UErrorCode& status) const {
#ifdef U_DEBUG_CALSVC
if(key.getDynamicClassID() != LocaleKey::getStaticClassID()) {
fprintf(stderr, "[%s]::create - not a LocaleKey!\n", fType);
}
#endif
const LocaleKey& lkey = (LocaleKey&)key;
Locale curLoc; // current locale
Locale canLoc; // Canonical locale
@ -138,7 +141,7 @@ protected:
key.currentID(str);
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "BasicCalendarFactory[%s] - cur %s, can %s\n", fType, (const char*)curLoc.getName(), (const char*)canLoc.getName());
fprintf(stderr, "BasicCalendarFactory[%s]::create() - cur %s, can %s\n", fType, (const char*)curLoc.getName(), (const char*)canLoc.getName());
#endif
if(str != fID) { // Do we handle this type?
@ -154,19 +157,16 @@ protected:
fflush(stderr);
#endif
if(!fType || !*fType || !uprv_strcmp(fType,"gregorian")) { // Gregorian (default)
if(!fType || !*fType || !uprv_strcmp(fType,"@calendar=gregorian")) { // Gregorian (default)
return new GregorianCalendar(canLoc, status);
} else if(!uprv_strcmp(fType, "japanese")) {
} else if(!uprv_strcmp(fType, "@calendar=japanese")) {
return new JapaneseCalendar(canLoc, status);
} else if(!uprv_strcmp(fType, "buddhist")) {
} else if(!uprv_strcmp(fType, "@calendar=buddhist")) {
return new BuddhistCalendar(canLoc, status);
#if defined (SRL_HAVE_ISLAMIC)
} else if(!uprv_strcmp(fType, "islamic-civil")) {
return new IslamicCalendar(canLoc, status);
} else if(!uprv_strcmp(fType, "islamic")) {
IslamicCalendar *i = new IslamicCalendar(canLoc, status);
i->setCivil(FALSE, status);
#endif
} else if(!uprv_strcmp(fType, "@calendar=islamic-civil")) {
return new IslamicCalendar(canLoc, status, IslamicCalendar::CIVIL);
} else if(!uprv_strcmp(fType, "@calendar=islamic")) {
return new IslamicCalendar(canLoc, status, IslamicCalendar::ASTRONOMICAL);
} else {
status = U_UNSUPPORTED_ERROR;
return NULL;
@ -201,7 +201,9 @@ class DefaultCalendarFactory : public ICUResourceBundleFactory {
fprintf(stderr, "DefaultCalendar factory %p: looking up %s, keyword: %s\n",
this, (const char*)loc.getName(), keyword);
#endif
return new UnicodeString(keyword,"");
UnicodeString *ret = new UnicodeString("@calendar=","");
(*ret) += UnicodeString(keyword, "");
return ret;
} else {
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "DefaultCalendar factory %p: looking up %s\n",
@ -228,6 +230,7 @@ class DefaultCalendarFactory : public ICUResourceBundleFactory {
}
UnicodeString myString = ures_getUnicodeStringByKey(rb, Calendar::kDefaultCalendar, &status);
myString = UnicodeString("@calendar=") + myString;
#ifdef U_DEBUG_CALSVC
int32_t len = 0;
@ -245,12 +248,13 @@ class DefaultCalendarFactory : public ICUResourceBundleFactory {
#ifdef U_DEBUG_CALSVC
{
char defCalStr[200];
if(len > 199) {
len = 199;
char defCalStr[200] = "@calendar=";
int32_t prefixLen = uprv_strlen(defCalStr);
if(len > (199-prefixLen)) {
len = (199-prefixLen);
}
u_UCharsToChars(defCal, defCalStr, len);
defCalStr[len]=0;
u_UCharsToChars(defCal, defCalStr+prefixLen, len);
defCalStr[len+prefixLen]=0;
fprintf(stderr, "DefaultCalendarFactory: looked up %s, got DefaultCalendar= %s\n", (const char*)loc.getName(), defCalStr);
}
#endif
@ -329,13 +333,11 @@ getService(void)
#endif
// Register all basic instances.
newservice->registerFactory(new BasicCalendarFactory("japanese"),status);
newservice->registerFactory(new BasicCalendarFactory("buddhist"),status);
newservice->registerFactory(new BasicCalendarFactory("gregorian"),status);
#if defined (SRL_HAVE_ISLAMIC)
newservice->registerFactory(new BasicCalendarFactory("islamic"),status);
newservice->registerFactory(new BasicCalendarFactory("islamic-civil"),status);
#endif
newservice->registerFactory(new BasicCalendarFactory("@calendar=japanese"),status);
newservice->registerFactory(new BasicCalendarFactory("@calendar=buddhist"),status);
newservice->registerFactory(new BasicCalendarFactory("@calendar=gregorian"),status);
newservice->registerFactory(new BasicCalendarFactory("@calendar=islamic"),status);
newservice->registerFactory(new BasicCalendarFactory("@calendar=islamic-civil"),status);
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "Done..\n");
@ -615,7 +617,7 @@ Calendar::createInstance(TimeZone* zone, const Locale& aLocale, UErrorCode& succ
tmp[len]=0;
#ifdef U_DEBUG_CALSVC
// fprintf(stderr, "createInstance(%s) told to look at %s..\n", (const char*)aLocale.getName(), tmp);
fprintf(stderr, "Calendar::createInstance(%s), fetched string %s..\n", (const char*)aLocale.getName(), tmp);
#endif
// Create a Locale over this string
@ -2971,6 +2973,7 @@ Calendar::getLocaleInternal(ULocDataLocaleType type, UErrorCode &status) const
U_NAMESPACE_END
U_CFUNC UBool calendar_cleanup(void) {
calendar_islamic_cleanup();
if (gService) {
delete gService;
gService = NULL;

View File

@ -0,0 +1,576 @@
/*
* Copyright (C) 2003, International Business Machines Corporation
* and others. All Rights Reserved.
******************************************************************************
*
* File ISLAMCAL.H
*
* Modification History:
*
* Date Name Description
* 10/14/2003 srl ported from java IslamicCalendar
*****************************************************************************
*/
#include "islamcal.h"
#if !UCONFIG_NO_FORMATTING
#include "mutex.h"
#include <float.h>
#include "gregoimp.h" // Math
#include "astro.h" // CalendarAstronomer
#include "uhash.h"
static const UDate HIJRA_MILLIS = -42521587200000.0; // 7/16/622 AD 00:00
// Debugging
#ifdef U_DEBUG_ISLAMCAL
# include <stdio.h>
# include <stdarg.h>
static void debug_islamcal_loc(const char *f, int32_t l)
{
fprintf(stderr, "%s:%d: ", f, l);
}
static void debug_islamcal_msg(const char *pat, ...)
{
va_list ap;
va_start(ap, pat);
vfprintf(stderr, pat, ap);
fflush(stderr);
}
// must use double parens, i.e.: U_DEBUG_ISLAMCAL_MSG(("four is: %d",4));
#define U_DEBUG_ISLAMCAL_MSG(x) {debug_islamcal_loc(__FILE__,__LINE__);debug_islamcal_msg x;}
#else
#define U_DEBUG_ISLAMCAL_MSG(x)
#endif
// --- The cache --
// cache of months
static UMTX astroLock = 0; // pod bay door lock
static UHashtable *monthCache = NULL;
static void createCache(UErrorCode &success) {
if(monthCache == NULL) {
monthCache = uhash_openSize(uhash_hashLong, uhash_compareLong, 32, &success);
}
}
/**
* Delete the cache, clean up.
* called by calendar_islamic_cleanup()
*/
static void deleteCache() {
if(monthCache != NULL) {
uhash_close(monthCache);
monthCache = NULL;
}
umtx_destroy(&astroLock);
astroLock = NULL;
}
static void putCache(int32_t month, int32_t start, UErrorCode &status) {
umtx_lock(&astroLock);
uhash_puti(monthCache, (void*)month, start, &status);
U_DEBUG_ISLAMCAL_MSG(("Add: m%d, st%d\n", month, start));
umtx_unlock(&astroLock);
}
int32_t getCache(int32_t month, UBool& found, UErrorCode &success) {
int32_t res = 0;
umtx_lock(&astroLock);
if(monthCache == NULL) {
createCache(success);
}
res = uhash_geti(monthCache, (void*)month);
umtx_unlock(&astroLock);
if(res!=0) {
found=TRUE;
} else {
found=FALSE;
}
U_DEBUG_ISLAMCAL_MSG(("Get: m%d, res%d, found%s\n", month, res, found?"Y":"N"));
return res;
}
U_NAMESPACE_BEGIN
// Implementation of the IslamicCalendar class
const char IslamicCalendar::fgClassID = 0; // Value is irrelevant
//-------------------------------------------------------------------------
// Constructors...
//-------------------------------------------------------------------------
const char *IslamicCalendar::getType() const {
if(civil==CIVIL) {
return "islamic-civil";
} else {
return "islamic";
}
}
Calendar* IslamicCalendar::clone() const {
return new IslamicCalendar(*this);
}
IslamicCalendar::IslamicCalendar(const Locale& aLocale, UErrorCode& success, ECivil beCivil)
: Calendar(TimeZone::createDefault(), aLocale, success),
civil(beCivil)
{
setTimeInMillis(getNow(), success); // Call this again now that the vtable is set up properly.
}
IslamicCalendar::IslamicCalendar(const IslamicCalendar& other) : Calendar(other), civil(other.civil) {
}
IslamicCalendar::~IslamicCalendar()
{
}
/**
* Determines whether this object uses the fixed-cycle Islamic civil calendar
* or an approximation of the religious, astronomical calendar.
*
* @param beCivil <code>true</code> to use the civil calendar,
* <code>false</code> to use the astronomical calendar.
* @draft ICU 2.4
*/
void IslamicCalendar::setCivil(ECivil beCivil, UErrorCode &status)
{
if (civil != beCivil) {
// The fields of the calendar will become invalid, because the calendar
// rules are different
UDate m = getTimeInMillis(status);
civil = beCivil;
clear();
setTimeInMillis(m, status);
}
}
/**
* Returns <code>true</code> if this object is using the fixed-cycle civil
* calendar, or <code>false</code> if using the religious, astronomical
* calendar.
* @draft ICU 2.4
*/
UBool IslamicCalendar::isCivil() {
return (civil == CIVIL);
}
//-------------------------------------------------------------------------
// Minimum / Maximum access functions
//-------------------------------------------------------------------------
static const int32_t LIMITS[UCAL_FIELD_COUNT][4] = {
// Minimum Greatest Least Maximum
// Minimum Maximum
{ 0, 0, 0, 0 }, // ERA
{ 1, 1, 5000000, 5000000 }, // YEAR
{ 0, 0, 11, 11 }, // MONTH
{ 1, 1, 51, 52 }, // WEEK_OF_YEAR
{ 0, 0, 5, 6 }, // WEEK_OF_MONTH
{ 1, 1, 29, 30 }, // DAY_OF_MONTH
{ 1, 1, 354, 355 }, // DAY_OF_YEAR
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK
{ -1, -1, 4, 5 }, // DAY_OF_WEEK_IN_MONTH
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET
{ -5000001, -5000001, 5000001, 5000001 }, // YEAR_WOY
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL
{ -5000000, -5000000, 5000000, 5000000 }, // EXTENDED_YEAR
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY
{/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1} // MILLISECONDS_IN_DAY
};
/**
* @draft ICU 2.4
*/
int32_t IslamicCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const {
return LIMITS[field][limitType];
}
//-------------------------------------------------------------------------
// Assorted calculation utilities
//
/**
* Determine whether a year is a leap year in the Islamic civil calendar
*/
UBool IslamicCalendar::civilLeapYear(int32_t year)
{
return (14 + 11 * year) % 30 < 11;
}
/**
* Return the day # on which the given year starts. Days are counted
* from the Hijri epoch, origin 0.
*/
int32_t IslamicCalendar::yearStart(int32_t year) {
if (civil == CIVIL) {
return (year-1)*354 + Math::floorDivide((3+11*year),30);
} else {
return trueMonthStart(12*(year-1));
}
}
/**
* Return the day # on which the given month starts. Days are counted
* from the Hijri epoch, origin 0.
*
* @param year The hijri year
* @param year The hijri month, 0-based
*/
int32_t IslamicCalendar::monthStart(int32_t year, int32_t month) const {
if (civil == CIVIL) {
return (int32_t)uprv_ceil(29.5*month)
+ (year-1)*354 + (int32_t)Math::floorDivide((3+11*year),30);
} else {
return trueMonthStart(12*(year-1) + month);
}
}
/**
* Find the day number on which a particular month of the true/lunar
* Islamic calendar starts.
*
* @param month The month in question, origin 0 from the Hijri epoch
*
* @return The day number on which the given month starts.
*/
int32_t IslamicCalendar::trueMonthStart(int32_t month) const
{
UBool found;
UErrorCode status = U_ZERO_ERROR;
int32_t start = getCache(month, found, status);
if (found==FALSE) {
// Make a guess at when the month started, using the average length
UDate origin = HIJRA_MILLIS
+ uprv_floor(month * CalendarAstronomer::SYNODIC_MONTH - 1) * kOneDay;
double age = moonAge(origin);
if (moonAge(origin) >= 0) {
// The month has already started
do {
origin -= kOneDay;
age = moonAge(origin);
} while (age >= 0);
}
else {
// Preceding month has not ended yet.
do {
origin += kOneDay;
age = moonAge(origin);
} while (age < 0);
}
start = (int32_t)Math::floorDivide((origin - HIJRA_MILLIS), (double)kOneDay) + 1;
putCache(month, start, status);
}
if(U_FAILURE(status)) {
start = 0;
}
return start;
}
/**
* Return the "age" of the moon at the given time; this is the difference
* in ecliptic latitude between the moon and the sun. This method simply
* calls CalendarAstronomer.moonAge, converts to degrees,
* and adjusts the result to be in the range [-180, 180].
*
* @param time The time at which the moon's age is desired,
* in millis since 1/1/1970.
*/
double IslamicCalendar::moonAge(UDate time)
{
double age = 0;
static CalendarAstronomer *astro = NULL;
umtx_lock(&astroLock);
if(astro == NULL) {
astro = new CalendarAstronomer();
}
astro->setTime(time);
age = astro->getMoonAge();
umtx_unlock(&astroLock);
// Convert to degrees and normalize...
age = age * 180 / CalendarAstronomer::PI;
if (age > 180) {
age = age - 360;
}
return age;
}
//----------------------------------------------------------------------
// Calendar framework
//----------------------------------------------------------------------
/**
* Return the length (in days) of the given month.
*
* @param year The hijri year
* @param year The hijri month, 0-based
* @draft ICU 2.4
*/
int32_t IslamicCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month) const {
int32_t length = 0;
if (civil == CIVIL) {
length = 29 + (month+1) % 2;
if (month == DHU_AL_HIJJAH && civilLeapYear(extendedYear)) {
length++;
}
} else {
month = 12*(extendedYear-1) + month;
length = trueMonthStart(month+1) - trueMonthStart(month) ;
}
return length;
}
/**
* Return the number of days in the given Islamic year
* @draft ICU 2.4
*/
int32_t IslamicCalendar::handleGetYearLength(int32_t extendedYear) const {
if (civil == CIVIL) {
return 354 + (civilLeapYear(extendedYear) ? 1 : 0);
} else {
int32_t month = 12*(extendedYear-1);
return (trueMonthStart(month + 12) - trueMonthStart(month));
}
}
//-------------------------------------------------------------------------
// Functions for converting from field values to milliseconds....
//-------------------------------------------------------------------------
// Return JD of start of given month/year
/**
* @draft ICU 2.4
*/
int32_t IslamicCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool useMonth) const {
return monthStart(eyear, month) + 1948439;
}
//-------------------------------------------------------------------------
// Functions for converting from milliseconds to field values
//-------------------------------------------------------------------------
/**
* @draft ICU 2.4
*/
int32_t IslamicCalendar::handleGetExtendedYear() {
int32_t year;
if (newerField(UCAL_EXTENDED_YEAR, UCAL_YEAR) == UCAL_EXTENDED_YEAR) {
year = internalGet(UCAL_EXTENDED_YEAR, 1); // Default to year 1
} else {
year = internalGet(UCAL_YEAR, 1); // Default to year 1
}
return year;
}
/**
* Override Calendar to compute several fields specific to the Islamic
* calendar system. These are:
*
* <ul><li>ERA
* <li>YEAR
* <li>MONTH
* <li>DAY_OF_MONTH
* <li>DAY_OF_YEAR
* <li>EXTENDED_YEAR</ul>
*
* The DAY_OF_WEEK and DOW_LOCAL fields are already set when this
* method is called. The getGregorianXxx() methods return Gregorian
* calendar equivalents for the given Julian day.
* @draft ICU 2.4
*/
void IslamicCalendar::handleComputeFields(int32_t julianDay, UErrorCode &status) {
int32_t year, month, dayOfMonth, dayOfYear;
UDate startDate;
int32_t days = julianDay - 1948440;
if (civil == CIVIL) {
// Use the civil calendar approximation, which is just arithmetic
year = (int)Math::floorDivide( (double)(30 * days + 10646) , 10631.0 );
month = (int32_t)uprv_ceil((days - 29 - yearStart(year)) / 29.5 );
month = month<11?month:11;
startDate = monthStart(year, month);
} else {
// Guess at the number of elapsed full months since the epoch
int32_t months = (int32_t)uprv_floor((double)days / CalendarAstronomer::SYNODIC_MONTH);
startDate = uprv_floor(months * CalendarAstronomer::SYNODIC_MONTH - 1);
if ( days - startDate >= 28 && moonAge(internalGetTime()) > 0) {
// If we're near the end of the month, assume next month and search backwards
months++;
}
// Find out the last time that the new moon was actually visible at this longitude
// This returns midnight the night that the moon was visible at sunset.
while ((startDate = trueMonthStart(months)) > days) {
// If it was after the date in question, back up a month and try again
months--;
}
year = months / 12 + 1;
month = months % 12;
}
dayOfMonth = (days - monthStart(year, month)) + 1;
// Now figure out the day of the year.
dayOfYear = (days - monthStart(year, 0) + 1);
internalSet(UCAL_ERA, 0);
internalSet(UCAL_YEAR, year);
internalSet(UCAL_EXTENDED_YEAR, year);
internalSet(UCAL_MONTH, month);
internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);
internalSet(UCAL_DAY_OF_YEAR, dayOfYear);
}
UBool
IslamicCalendar::inDaylightTime(UErrorCode& status) const
{
// copied from GregorianCalendar
if (U_FAILURE(status) || !getTimeZone().useDaylightTime())
return FALSE;
// Force an update of the state of the Calendar.
((IslamicCalendar*)this)->complete(status); // cast away const
return (UBool)(U_SUCCESS(status) ? (internalGet(UCAL_DST_OFFSET) != 0) : FALSE);
}
// deprecated
void
IslamicCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) {
Calendar::roll((UCalendarDateFields) field, amount, status);
}
// default century
const UDate IslamicCalendar::fgSystemDefaultCentury = DBL_MIN;
const int32_t IslamicCalendar::fgSystemDefaultCenturyYear = -1;
UDate IslamicCalendar::fgSystemDefaultCenturyStart = DBL_MIN;
int32_t IslamicCalendar::fgSystemDefaultCenturyStartYear = -1;
UBool IslamicCalendar::haveDefaultCentury() const
{
return TRUE;
}
UDate IslamicCalendar::defaultCenturyStart() const
{
return internalGetDefaultCenturyStart();
}
int32_t IslamicCalendar::defaultCenturyStartYear() const
{
return internalGetDefaultCenturyStartYear();
}
UDate
IslamicCalendar::internalGetDefaultCenturyStart() const
{
// lazy-evaluate systemDefaultCenturyStart
UBool needsUpdate;
{
Mutex m;
needsUpdate = (fgSystemDefaultCenturyStart == fgSystemDefaultCentury);
}
if (needsUpdate) {
initializeSystemDefaultCentury();
}
// use defaultCenturyStart unless it's the flag value;
// then use systemDefaultCenturyStart
return fgSystemDefaultCenturyStart;
}
int32_t
IslamicCalendar::internalGetDefaultCenturyStartYear() const
{
// lazy-evaluate systemDefaultCenturyStartYear
UBool needsUpdate;
{
Mutex m;
needsUpdate = (fgSystemDefaultCenturyStart == fgSystemDefaultCentury);
}
if (needsUpdate) {
initializeSystemDefaultCentury();
}
// use defaultCenturyStart unless it's the flag value;
// then use systemDefaultCenturyStartYear
return fgSystemDefaultCenturyStartYear;
}
void
IslamicCalendar::initializeSystemDefaultCentury()
{
// initialize systemDefaultCentury and systemDefaultCenturyYear based
// on the current time. They'll be set to 80 years before
// the current time.
// No point in locking as it should be idempotent.
if (fgSystemDefaultCenturyStart == fgSystemDefaultCentury)
{
UErrorCode status = U_ZERO_ERROR;
Calendar *calendar = new IslamicCalendar(Locale("ar@calendar=islamic-civil"),status);
if (calendar != NULL && U_SUCCESS(status))
{
calendar->setTime(Calendar::getNow(), status);
calendar->add(UCAL_YEAR, -80, status);
UDate newStart = calendar->getTime(status);
int32_t newYear = calendar->get(UCAL_YEAR, status);
{
Mutex m;
fgSystemDefaultCenturyStart = newStart;
fgSystemDefaultCenturyStartYear = newYear;
}
delete calendar;
}
// We have no recourse upon failure unless we want to propagate the failure
// out.
}
}
U_NAMESPACE_END
U_CFUNC UBool calendar_islamic_cleanup(void) {
deleteCache();
return TRUE;
}
#endif

View File

@ -0,0 +1,486 @@
/*
* Copyright (C) 2003, International Business Machines Corporation
* and others. All Rights Reserved.
******************************************************************************
*
* File ISLAMCAL.H
*
* Modification History:
*
* Date Name Description
* 10/14/2003 srl ported from java IslamicCalendar
*****************************************************************************
*/
#ifndef ISLAMCAL_H
#define ISLAMCAL_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/calendar.h"
/**
* <code>IslamicCalendar</code> is a subclass of <code>Calendar</code>
* that that implements the Islamic civil and religious calendars. It
* is used as the civil calendar in most of the Arab world and the
* liturgical calendar of the Islamic faith worldwide. This calendar
* is also known as the "Hijri" calendar, since it starts at the time
* of Mohammed's emigration (or "hijra") to Medinah on Thursday,
* July 15, 622 AD (Julian).
* <p>
* The Islamic calendar is strictly lunar, and thus an Islamic year of twelve
* lunar months does not correspond to the solar year used by most other
* calendar systems, including the Gregorian. An Islamic year is, on average,
* about 354 days long, so each successive Islamic year starts about 11 days
* earlier in the corresponding Gregorian year.
* <p>
* Each month of the calendar starts when the new moon's crescent is visible
* at sunset. However, in order to keep the time fields in this class
* synchronized with those of the other calendars and with local clock time,
* we treat days and months as beginning at midnight,
* roughly 6 hours after the corresponding sunset.
* <p>
* There are two main variants of the Islamic calendar in existence. The first
* is the <em>civil</em> calendar, which uses a fixed cycle of alternating 29-
* and 30-day months, with a leap day added to the last month of 11 out of
* every 30 years. This calendar is easily calculated and thus predictable in
* advance, so it is used as the civil calendar in a number of Arab countries.
* This is the default behavior of a newly-created <code>IslamicCalendar</code>
* object.
* <p>
* The Islamic <em>religious</em> calendar, however, is based on the <em>observation</em>
* of the crescent moon. It is thus affected by the position at which the
* observations are made, seasonal variations in the time of sunset, the
* eccentricities of the moon's orbit, and even the weather at the observation
* site. This makes it impossible to calculate in advance, and it causes the
* start of a month in the religious calendar to differ from the civil calendar
* by up to three days.
* <p>
* Using astronomical calculations for the position of the sun and moon, the
* moon's illumination, and other factors, it is possible to determine the start
* of a lunar month with a fairly high degree of certainty. However, these
* calculations are extremely complicated and thus slow, so most algorithms,
* including the one used here, are only approximations of the true astronical
* calculations. At present, the approximations used in this class are fairly
* simplistic; they will be improved in later versions of the code.
* <p>
* The {@link #setCivil setCivil} method determines
* which approach is used to determine the start of a month. By default, the
* fixed-cycle civil calendar is used. However, if <code>setCivil(false)</code>
* is called, an approximation of the true lunar calendar will be used.
*
* @see GregorianCalendar
*
* @author Laura Werner
* @author Alan Liu
* @author Steven R. Loomis
* @internal
*/
class U_I18N_API IslamicCalendar : public Calendar {
public:
//-------------------------------------------------------------------------
// Constants...
//-------------------------------------------------------------------------
/**
* Calendar type - civil or religious
* @internal
*/
enum ECivil {
ASTRONOMICAL,
CIVIL
};
/**
* Constants for the months
* @internal
*/
enum EMonths {
/**
* Constant for Muharram, the 1st month of the Islamic year.
* @internal
*/
MUHARRAM = 0,
/**
* Constant for Safar, the 2nd month of the Islamic year.
* @internal
*/
SAFAR = 1,
/**
* Constant for Rabi' al-awwal (or Rabi' I), the 3rd month of the Islamic year.
* @internal
*/
RABI_1 = 2,
/**
* Constant for Rabi' al-thani or (Rabi' II), the 4th month of the Islamic year.
* @internal
*/
RABI_2 = 3,
/**
* Constant for Jumada al-awwal or (Jumada I), the 5th month of the Islamic year.
* @internal
*/
JUMADA_1 = 4,
/**
* Constant for Jumada al-thani or (Jumada II), the 6th month of the Islamic year.
* @internal
*/
JUMADA_2 = 5,
/**
* Constant for Rajab, the 7th month of the Islamic year.
* @internal
*/
RAJAB = 6,
/**
* Constant for Sha'ban, the 8th month of the Islamic year.
* @internal
*/
SHABAN = 7,
/**
* Constant for Ramadan, the 9th month of the Islamic year.
* @internal
*/
RAMADAN = 8,
/**
* Constant for Shawwal, the 10th month of the Islamic year.
* @internal
*/
SHAWWAL = 9,
/**
* Constant for Dhu al-Qi'dah, the 11th month of the Islamic year.
* @internal
*/
DHU_AL_QIDAH = 10,
/**
* Constant for Dhu al-Hijjah, the 12th month of the Islamic year.
* @internal
*/
DHU_AL_HIJJAH = 11,
ISLAMIC_MONTH_MAX
};
//-------------------------------------------------------------------------
// Constructors...
//-------------------------------------------------------------------------
/**
* Constructs an IslamicCalendar based on the current time in the default time zone
* with the given locale.
*
* @param aLocale The given locale.
* @param success Indicates the status of IslamicCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @param beCivil Whether the calendar should be civil (default-TRUE) or religious (FALSE)
* @internal
*/
IslamicCalendar(const Locale& aLocale, UErrorCode &success, ECivil beCivil = CIVIL);
/**
* Copy Constructor
* @internal
*/
IslamicCalendar(const IslamicCalendar& other);
/**
* Destructor.
* @internal
*/
virtual ~IslamicCalendar();
/**
* Determines whether this object uses the fixed-cycle Islamic civil calendar
* or an approximation of the religious, astronomical calendar.
*
* @param beCivil <code>CIVIL</code> to use the civil calendar,
* <code>ASTRONOMICAL</code> to use the astronomical calendar.
* @internal
*/
void setCivil(ECivil beCivil, UErrorCode &status);
/**
* Returns <code>true</code> if this object is using the fixed-cycle civil
* calendar, or <code>false</code> if using the religious, astronomical
* calendar.
* @internal
*/
UBool isCivil();
// TODO: copy c'tor, etc
// clone
virtual Calendar* clone() const;
private:
/**
* Determine whether a year is a leap year in the Islamic civil calendar
*/
static UBool civilLeapYear(int32_t year);
/**
* Return the day # on which the given year starts. Days are counted
* from the Hijri epoch, origin 0.
*/
int32_t yearStart(int32_t year);
/**
* Return the day # on which the given month starts. Days are counted
* from the Hijri epoch, origin 0.
*
* @param year The hijri year
* @param year The hijri month, 0-based
*/
int32_t monthStart(int year, int month) const;
/**
* Find the day number on which a particular month of the true/lunar
* Islamic calendar starts.
*
* @param month The month in question, origin 0 from the Hijri epoch
*
* @return The day number on which the given month starts.
*/
int32_t trueMonthStart(int32_t month) const;
/**
* Return the "age" of the moon at the given time; this is the difference
* in ecliptic latitude between the moon and the sun. This method simply
* calls CalendarAstronomer.moonAge, converts to degrees,
* and adjusts the resultto be in the range [-180, 180].
*
* @param time The time at which the moon's age is desired,
* in millis since 1/1/1970.
*/
static double moonAge(UDate time);
//-------------------------------------------------------------------------
// Internal data....
//
/**
* <code>CIVIL</code> if this object uses the fixed-cycle Islamic civil calendar,
* and <code>ASTRONOMICAL</code> if it approximates the true religious calendar using
* astronomical calculations for the time of the new moon.
*/
ECivil civil;
//----------------------------------------------------------------------
// Calendar framework
//----------------------------------------------------------------------
protected:
/**
* @internal
*/
virtual int32_t handleGetLimit(UCalendarDateFields field, ELimitType limitType) const;
/**
* Return the length (in days) of the given month.
*
* @param year The hijri year
* @param year The hijri month, 0-based
* @internal
*/
virtual int32_t handleGetMonthLength(int32_t extendedYear, int32_t month) const;
/**
* Return the number of days in the given Islamic year
* @internal
*/
virtual int32_t handleGetYearLength(int32_t extendedYear) const;
//-------------------------------------------------------------------------
// Functions for converting from field values to milliseconds....
//-------------------------------------------------------------------------
// Return JD of start of given month/year
/**
* @internal
*/
virtual int32_t handleComputeMonthStart(int32_t eyear, int32_t month, UBool useMonth) const;
//-------------------------------------------------------------------------
// Functions for converting from milliseconds to field values
//-------------------------------------------------------------------------
/**
* @internal
*/
virtual int32_t handleGetExtendedYear();
/**
* Override Calendar to compute several fields specific to the Islamic
* calendar system. These are:
*
* <ul><li>ERA
* <li>YEAR
* <li>MONTH
* <li>DAY_OF_MONTH
* <li>DAY_OF_YEAR
* <li>EXTENDED_YEAR</ul>
*
* The DAY_OF_WEEK and DOW_LOCAL fields are already set when this
* method is called. The getGregorianXxx() methods return Gregorian
* calendar equivalents for the given Julian day.
* @internal
*/
virtual void handleComputeFields(int32_t julianDay, UErrorCode &status);
// UObject stuff
public:
/**
* @return The class ID for this object. All objects of a given class have the
* same class ID. Objects of other classes have different class IDs.
* @internal
*/
virtual UClassID getDynamicClassID(void) const;
/**
* Return the class ID for this class. This is useful only for comparing to a return
* value from getDynamicClassID(). For example:
*
* Base* polymorphic_pointer = createPolymorphicObject();
* if (polymorphic_pointer->getDynamicClassID() ==
* Derived::getStaticClassID()) ...
*
* @return The class ID for all objects of this class.
* @internal
*/
static inline UClassID getStaticClassID(void);
/**
* return the calendar type, "buddhist".
*
* @return calendar type
* @internal
*/
virtual const char * getType() const;
private:
IslamicCalendar(); // default constructor not implemented
static const char fgClassID;
// Default century.
protected:
/**
* (Overrides Calendar) Return true if the current date for this Calendar is in
* Daylight Savings Time. Recognizes DST_OFFSET, if it is set.
*
* @param status Fill-in parameter which receives the status of this operation.
* @return True if the current date for this Calendar is in Daylight Savings Time,
* false, otherwise.
* @internal
*/
virtual UBool inDaylightTime(UErrorCode& status) const;
/**
* Returns TRUE because the Islamic Calendar does have a default century
* @internal
*/
virtual UBool haveDefaultCentury() const;
/**
* Returns the date of the start of the default century
* @return start of century - in milliseconds since epoch, 1970
* @internal
*/
virtual UDate defaultCenturyStart() const;
/**
* Returns the year in which the default century begins
* @internal
*/
virtual int32_t defaultCenturyStartYear() const;
private: // default century stuff.
/**
* The system maintains a static default century start date. This is initialized
* the first time it is used. Before then, it is set to SYSTEM_DEFAULT_CENTURY to
* indicate an uninitialized state. Once the system default century date and year
* are set, they do not change.
*/
static UDate fgSystemDefaultCenturyStart;
/**
* See documentation for systemDefaultCenturyStart.
*/
static int32_t fgSystemDefaultCenturyStartYear;
/**
* Default value that indicates the defaultCenturyStartYear is unitialized
*/
static const int32_t fgSystemDefaultCenturyYear;
/**
* start of default century, as a date
*/
static const UDate fgSystemDefaultCentury;
/**
* Returns the beginning date of the 100-year window that dates
* with 2-digit years are considered to fall within.
*/
UDate internalGetDefaultCenturyStart(void) const;
/**
* Returns the first year of the 100-year window that dates with
* 2-digit years are considered to fall within.
*/
int32_t internalGetDefaultCenturyStartYear(void) const;
/**
* Initializes the 100-year window that dates with 2-digit years
* are considered to fall within so that its start date is 80 years
* before the current time.
*/
static void initializeSystemDefaultCentury(void);
public:
// deprecates
/**
* (Overrides Calendar) Rolls up or down by the given amount in the specified field.
* For more information, see the documentation for Calendar::roll().
*
* @param field The time field.
* @param amount Indicates amount to roll.
* @param status Output param set to success/failure code on exit. If any value
* previously set in the time field is invalid, this will be set to
* an error status.
* @deprecated ICU 2.6 Use roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead. (here for subclass compat)
*/
virtual void roll(EDateFields field, int32_t amount, UErrorCode& status);
};
inline UClassID
IslamicCalendar::getStaticClassID(void)
{ return (UClassID)&fgClassID; }
inline UClassID
IslamicCalendar::getDynamicClassID(void) const
{ return IslamicCalendar::getStaticClassID(); }
// INTERNAL - for cleanup
// clean up the astronomical data & cache
U_CFUNC UBool calendar_islamic_cleanup(void);
#endif
#endif