michael@0: /* michael@0: ******************************************************************************* michael@0: * Copyright (C) 1997-2013, International Business Machines Corporation and * michael@0: * others. All Rights Reserved. * michael@0: ******************************************************************************* michael@0: * michael@0: * File CALENDAR.CPP michael@0: * michael@0: * Modification History: michael@0: * michael@0: * Date Name Description michael@0: * 02/03/97 clhuang Creation. michael@0: * 04/22/97 aliu Cleaned up, fixed memory leak, made michael@0: * setWeekCountData() more robust. michael@0: * Moved platform code to TPlatformUtilities. michael@0: * 05/01/97 aliu Made equals(), before(), after() arguments const. michael@0: * 05/20/97 aliu Changed logic of when to compute fields and time michael@0: * to fix bugs. michael@0: * 08/12/97 aliu Added equivalentTo. Misc other fixes. michael@0: * 07/28/98 stephen Sync up with JDK 1.2 michael@0: * 09/02/98 stephen Sync with JDK 1.2 8/31 build (getActualMin/Max) michael@0: * 03/17/99 stephen Changed adoptTimeZone() - now fAreFieldsSet is michael@0: * set to FALSE to force update of time. michael@0: ******************************************************************************* michael@0: */ michael@0: michael@0: #include "utypeinfo.h" // for 'typeid' to work michael@0: michael@0: #include "unicode/utypes.h" michael@0: michael@0: #if !UCONFIG_NO_FORMATTING michael@0: michael@0: #include "unicode/gregocal.h" michael@0: #include "unicode/basictz.h" michael@0: #include "unicode/simpletz.h" michael@0: #include "unicode/rbtz.h" michael@0: #include "unicode/vtzone.h" michael@0: #include "gregoimp.h" michael@0: #include "buddhcal.h" michael@0: #include "taiwncal.h" michael@0: #include "japancal.h" michael@0: #include "islamcal.h" michael@0: #include "hebrwcal.h" michael@0: #include "persncal.h" michael@0: #include "indiancal.h" michael@0: #include "chnsecal.h" michael@0: #include "coptccal.h" michael@0: #include "dangical.h" michael@0: #include "ethpccal.h" michael@0: #include "unicode/calendar.h" michael@0: #include "cpputils.h" michael@0: #include "servloc.h" michael@0: #include "ucln_in.h" michael@0: #include "cstring.h" michael@0: #include "locbased.h" michael@0: #include "uresimp.h" michael@0: #include "ustrenum.h" michael@0: #include "uassert.h" michael@0: #include "olsontz.h" michael@0: michael@0: #if !UCONFIG_NO_SERVICE michael@0: static icu::ICULocaleService* gService = NULL; michael@0: static icu::UInitOnce gServiceInitOnce = U_INITONCE_INITIALIZER; michael@0: #endif michael@0: michael@0: // INTERNAL - for cleanup michael@0: michael@0: U_CDECL_BEGIN michael@0: static UBool calendar_cleanup(void) { michael@0: #if !UCONFIG_NO_SERVICE michael@0: if (gService) { michael@0: delete gService; michael@0: gService = NULL; michael@0: } michael@0: gServiceInitOnce.reset(); michael@0: #endif michael@0: return TRUE; michael@0: } michael@0: U_CDECL_END michael@0: michael@0: // ------------------------------------------ michael@0: // michael@0: // Registration michael@0: // michael@0: //------------------------------------------- michael@0: //#define U_DEBUG_CALSVC 1 michael@0: // michael@0: michael@0: #if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL) michael@0: michael@0: /** michael@0: * fldName was removed as a duplicate implementation. michael@0: * use udbg_ services instead, michael@0: * which depend on include files and library from ../tools/toolutil, the following circular link: michael@0: * CPPFLAGS+=-I$(top_srcdir)/tools/toolutil michael@0: * LIBS+=$(LIBICUTOOLUTIL) michael@0: */ michael@0: #include "udbgutil.h" michael@0: #include michael@0: michael@0: /** michael@0: * convert a UCalendarDateFields into a string - for debugging michael@0: * @param f field enum michael@0: * @return static string to the field name michael@0: * @internal michael@0: */ michael@0: michael@0: const char* fldName(UCalendarDateFields f) { michael@0: return udbg_enumName(UDBG_UCalendarDateFields, (int32_t)f); michael@0: } michael@0: michael@0: #if UCAL_DEBUG_DUMP michael@0: // from CalendarTest::calToStr - but doesn't modify contents. michael@0: void ucal_dump(const Calendar &cal) { michael@0: cal.dump(); michael@0: } michael@0: michael@0: void Calendar::dump() const { michael@0: int i; michael@0: fprintf(stderr, "@calendar=%s, timeset=%c, fieldset=%c, allfields=%c, virtualset=%c, t=%.2f", michael@0: getType(), fIsTimeSet?'y':'n', fAreFieldsSet?'y':'n', fAreAllFieldsSet?'y':'n', michael@0: fAreFieldsVirtuallySet?'y':'n', michael@0: fTime); michael@0: michael@0: // can add more things here: DST, zone, etc. michael@0: fprintf(stderr, "\n"); michael@0: for(i = 0;i ja_JP@calendar=japanese michael@0: int32_t canonicalLen = uloc_canonicalize(locid, canonicalName, sizeof(canonicalName) - 1, &status); michael@0: if (U_FAILURE(status)) { michael@0: return CALTYPE_GREGORIAN; michael@0: } michael@0: canonicalName[canonicalLen] = 0; // terminate michael@0: michael@0: char calTypeBuf[32]; michael@0: int32_t calTypeBufLen; michael@0: michael@0: calTypeBufLen = uloc_getKeywordValue(canonicalName, "calendar", calTypeBuf, sizeof(calTypeBuf) - 1, &status); michael@0: if (U_SUCCESS(status)) { michael@0: calTypeBuf[calTypeBufLen] = 0; michael@0: calType = getCalendarType(calTypeBuf); michael@0: if (calType != CALTYPE_UNKNOWN) { michael@0: return calType; michael@0: } michael@0: } michael@0: status = U_ZERO_ERROR; michael@0: michael@0: // when calendar keyword is not available or not supported, read supplementalData michael@0: // to get the default calendar type for the locale's region michael@0: char region[ULOC_COUNTRY_CAPACITY]; michael@0: int32_t regionLen = 0; michael@0: regionLen = uloc_getCountry(canonicalName, region, sizeof(region) - 1, &status); michael@0: if (regionLen == 0) { michael@0: char fullLoc[256]; michael@0: uloc_addLikelySubtags(locid, fullLoc, sizeof(fullLoc) - 1, &status); michael@0: regionLen = uloc_getCountry(fullLoc, region, sizeof(region) - 1, &status); michael@0: } michael@0: if (U_FAILURE(status)) { michael@0: return CALTYPE_GREGORIAN; michael@0: } michael@0: region[regionLen] = 0; michael@0: michael@0: // Read preferred calendar values from supplementalData calendarPreference michael@0: UResourceBundle *rb = ures_openDirect(NULL, "supplementalData", &status); michael@0: ures_getByKey(rb, "calendarPreferenceData", rb, &status); michael@0: UResourceBundle *order = ures_getByKey(rb, region, NULL, &status); michael@0: if (status == U_MISSING_RESOURCE_ERROR && rb != NULL) { michael@0: status = U_ZERO_ERROR; michael@0: order = ures_getByKey(rb, "001", NULL, &status); michael@0: } michael@0: michael@0: calTypeBuf[0] = 0; michael@0: if (U_SUCCESS(status) && order != NULL) { michael@0: // the first calender type is the default for the region michael@0: int32_t len = 0; michael@0: const UChar *uCalType = ures_getStringByIndex(order, 0, &len, &status); michael@0: if (len < (int32_t)sizeof(calTypeBuf)) { michael@0: u_UCharsToChars(uCalType, calTypeBuf, len); michael@0: *(calTypeBuf + len) = 0; // terminate; michael@0: calType = getCalendarType(calTypeBuf); michael@0: } michael@0: } michael@0: michael@0: ures_close(order); michael@0: ures_close(rb); michael@0: michael@0: if (calType == CALTYPE_UNKNOWN) { michael@0: // final fallback michael@0: calType = CALTYPE_GREGORIAN; michael@0: } michael@0: return calType; michael@0: } michael@0: michael@0: static Calendar *createStandardCalendar(ECalType calType, const Locale &loc, UErrorCode& status) { michael@0: Calendar *cal = NULL; michael@0: michael@0: switch (calType) { michael@0: case CALTYPE_GREGORIAN: michael@0: cal = new GregorianCalendar(loc, status); michael@0: break; michael@0: case CALTYPE_JAPANESE: michael@0: cal = new JapaneseCalendar(loc, status); michael@0: break; michael@0: case CALTYPE_BUDDHIST: michael@0: cal = new BuddhistCalendar(loc, status); michael@0: break; michael@0: case CALTYPE_ROC: michael@0: cal = new TaiwanCalendar(loc, status); michael@0: break; michael@0: case CALTYPE_PERSIAN: michael@0: cal = new PersianCalendar(loc, status); michael@0: break; michael@0: case CALTYPE_ISLAMIC_TBLA: michael@0: cal = new IslamicCalendar(loc, status, IslamicCalendar::TBLA); michael@0: break; michael@0: case CALTYPE_ISLAMIC_CIVIL: michael@0: cal = new IslamicCalendar(loc, status, IslamicCalendar::CIVIL); michael@0: break; michael@0: case CALTYPE_ISLAMIC_RGSA: michael@0: // default any region specific not handled individually to islamic michael@0: case CALTYPE_ISLAMIC: michael@0: cal = new IslamicCalendar(loc, status, IslamicCalendar::ASTRONOMICAL); michael@0: break; michael@0: case CALTYPE_ISLAMIC_UMALQURA: michael@0: cal = new IslamicCalendar(loc, status, IslamicCalendar::UMALQURA); michael@0: break; michael@0: case CALTYPE_HEBREW: michael@0: cal = new HebrewCalendar(loc, status); michael@0: break; michael@0: case CALTYPE_CHINESE: michael@0: cal = new ChineseCalendar(loc, status); michael@0: break; michael@0: case CALTYPE_INDIAN: michael@0: cal = new IndianCalendar(loc, status); michael@0: break; michael@0: case CALTYPE_COPTIC: michael@0: cal = new CopticCalendar(loc, status); michael@0: break; michael@0: case CALTYPE_ETHIOPIC: michael@0: cal = new EthiopicCalendar(loc, status, EthiopicCalendar::AMETE_MIHRET_ERA); michael@0: break; michael@0: case CALTYPE_ETHIOPIC_AMETE_ALEM: michael@0: cal = new EthiopicCalendar(loc, status, EthiopicCalendar::AMETE_ALEM_ERA); michael@0: break; michael@0: case CALTYPE_ISO8601: michael@0: cal = new GregorianCalendar(loc, status); michael@0: cal->setFirstDayOfWeek(UCAL_MONDAY); michael@0: cal->setMinimalDaysInFirstWeek(4); michael@0: break; michael@0: case CALTYPE_DANGI: michael@0: cal = new DangiCalendar(loc, status); michael@0: break; michael@0: default: michael@0: status = U_UNSUPPORTED_ERROR; michael@0: } michael@0: return cal; michael@0: } michael@0: michael@0: michael@0: #if !UCONFIG_NO_SERVICE michael@0: michael@0: // ------------------------------------- michael@0: michael@0: /** michael@0: * a Calendar Factory which creates the "basic" calendar types, that is, those michael@0: * shipped with ICU. michael@0: */ michael@0: class BasicCalendarFactory : public LocaleKeyFactory { michael@0: public: michael@0: /** michael@0: * @param calendarType static const string (caller owns storage - will be aliased) to calendar type michael@0: */ michael@0: BasicCalendarFactory() michael@0: : LocaleKeyFactory(LocaleKeyFactory::INVISIBLE) { } michael@0: michael@0: virtual ~BasicCalendarFactory(); michael@0: michael@0: protected: michael@0: //virtual UBool isSupportedID( const UnicodeString& id, UErrorCode& status) const { michael@0: // if(U_FAILURE(status)) { michael@0: // return FALSE; michael@0: // } michael@0: // char keyword[ULOC_FULLNAME_CAPACITY]; michael@0: // getCalendarKeyword(id, keyword, (int32_t)sizeof(keyword)); michael@0: // return isStandardSupportedKeyword(keyword, status); michael@0: //} michael@0: michael@0: virtual void updateVisibleIDs(Hashtable& result, UErrorCode& status) const michael@0: { michael@0: if (U_SUCCESS(status)) { michael@0: for(int32_t i=0;gCalTypes[i] != NULL;i++) { michael@0: UnicodeString id((UChar)0x40); /* '@' a variant character */ michael@0: id.append(UNICODE_STRING_SIMPLE("calendar=")); michael@0: id.append(UnicodeString(gCalTypes[i], -1, US_INV)); michael@0: result.put(id, (void*)this, status); michael@0: } michael@0: } michael@0: } michael@0: michael@0: virtual UObject* create(const ICUServiceKey& key, const ICUService* /*service*/, UErrorCode& status) const { michael@0: #ifdef U_DEBUG_CALSVC michael@0: if(dynamic_cast(&key) == NULL) { michael@0: fprintf(stderr, "::create - not a LocaleKey!\n"); michael@0: } michael@0: #endif michael@0: const LocaleKey& lkey = (LocaleKey&)key; michael@0: Locale curLoc; // current locale michael@0: Locale canLoc; // Canonical locale michael@0: michael@0: lkey.currentLocale(curLoc); michael@0: lkey.canonicalLocale(canLoc); michael@0: michael@0: char keyword[ULOC_FULLNAME_CAPACITY]; michael@0: UnicodeString str; michael@0: michael@0: key.currentID(str); michael@0: getCalendarKeyword(str, keyword, (int32_t) sizeof(keyword)); michael@0: michael@0: #ifdef U_DEBUG_CALSVC michael@0: fprintf(stderr, "BasicCalendarFactory::create() - cur %s, can %s\n", (const char*)curLoc.getName(), (const char*)canLoc.getName()); michael@0: #endif michael@0: michael@0: if(!isStandardSupportedKeyword(keyword,status)) { // Do we handle this type? michael@0: #ifdef U_DEBUG_CALSVC michael@0: michael@0: fprintf(stderr, "BasicCalendarFactory - not handling %s.[%s]\n", (const char*) curLoc.getName(), tmp ); michael@0: #endif michael@0: return NULL; michael@0: } michael@0: michael@0: return createStandardCalendar(getCalendarType(keyword), canLoc, status); michael@0: } michael@0: }; michael@0: michael@0: BasicCalendarFactory::~BasicCalendarFactory() {} michael@0: michael@0: /** michael@0: * A factory which looks up the DefaultCalendar resource to determine which class of calendar to use michael@0: */ michael@0: michael@0: class DefaultCalendarFactory : public ICUResourceBundleFactory { michael@0: public: michael@0: DefaultCalendarFactory() : ICUResourceBundleFactory() { } michael@0: virtual ~DefaultCalendarFactory(); michael@0: protected: michael@0: virtual UObject* create(const ICUServiceKey& key, const ICUService* /*service*/, UErrorCode& status) const { michael@0: michael@0: LocaleKey &lkey = (LocaleKey&)key; michael@0: Locale loc; michael@0: lkey.currentLocale(loc); michael@0: michael@0: UnicodeString *ret = new UnicodeString(); michael@0: if (ret == NULL) { michael@0: status = U_MEMORY_ALLOCATION_ERROR; michael@0: } else { michael@0: ret->append((UChar)0x40); // '@' is a variant character michael@0: ret->append(UNICODE_STRING("calendar=", 9)); michael@0: ret->append(UnicodeString(gCalTypes[getCalendarTypeForLocale(loc.getName())], -1, US_INV)); michael@0: } michael@0: return ret; michael@0: } michael@0: }; michael@0: michael@0: DefaultCalendarFactory::~DefaultCalendarFactory() {} michael@0: michael@0: // ------------------------------------- michael@0: class CalendarService : public ICULocaleService { michael@0: public: michael@0: CalendarService() michael@0: : ICULocaleService(UNICODE_STRING_SIMPLE("Calendar")) michael@0: { michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: registerFactory(new DefaultCalendarFactory(), status); michael@0: } michael@0: michael@0: virtual ~CalendarService(); michael@0: michael@0: virtual UObject* cloneInstance(UObject* instance) const { michael@0: UnicodeString *s = dynamic_cast(instance); michael@0: if(s != NULL) { michael@0: return s->clone(); michael@0: } else { michael@0: #ifdef U_DEBUG_CALSVC_F michael@0: UErrorCode status2 = U_ZERO_ERROR; michael@0: fprintf(stderr, "Cloning a %s calendar with tz=%ld\n", ((Calendar*)instance)->getType(), ((Calendar*)instance)->get(UCAL_ZONE_OFFSET, status2)); michael@0: #endif michael@0: return ((Calendar*)instance)->clone(); michael@0: } michael@0: } michael@0: michael@0: virtual UObject* handleDefault(const ICUServiceKey& key, UnicodeString* /*actualID*/, UErrorCode& status) const { michael@0: LocaleKey& lkey = (LocaleKey&)key; michael@0: //int32_t kind = lkey.kind(); michael@0: michael@0: Locale loc; michael@0: lkey.canonicalLocale(loc); michael@0: michael@0: #ifdef U_DEBUG_CALSVC michael@0: Locale loc2; michael@0: lkey.currentLocale(loc2); michael@0: fprintf(stderr, "CalSvc:handleDefault for currentLoc %s, canloc %s\n", (const char*)loc.getName(), (const char*)loc2.getName()); michael@0: #endif michael@0: Calendar *nc = new GregorianCalendar(loc, status); michael@0: michael@0: #ifdef U_DEBUG_CALSVC michael@0: UErrorCode status2 = U_ZERO_ERROR; michael@0: fprintf(stderr, "New default calendar has tz=%d\n", ((Calendar*)nc)->get(UCAL_ZONE_OFFSET, status2)); michael@0: #endif michael@0: return nc; michael@0: } michael@0: michael@0: virtual UBool isDefault() const { michael@0: return countFactories() == 1; michael@0: } michael@0: }; michael@0: michael@0: CalendarService::~CalendarService() {} michael@0: michael@0: // ------------------------------------- michael@0: michael@0: static inline UBool michael@0: isCalendarServiceUsed() { michael@0: return !gServiceInitOnce.isReset(); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: static void U_CALLCONV michael@0: initCalendarService(UErrorCode &status) michael@0: { michael@0: #ifdef U_DEBUG_CALSVC michael@0: fprintf(stderr, "Spinning up Calendar Service\n"); michael@0: #endif michael@0: ucln_i18n_registerCleanup(UCLN_I18N_CALENDAR, calendar_cleanup); michael@0: gService = new CalendarService(); michael@0: if (gService == NULL) { michael@0: status = U_MEMORY_ALLOCATION_ERROR; michael@0: return; michael@0: } michael@0: #ifdef U_DEBUG_CALSVC michael@0: fprintf(stderr, "Registering classes..\n"); michael@0: #endif michael@0: michael@0: // Register all basic instances. michael@0: gService->registerFactory(new BasicCalendarFactory(),status); michael@0: michael@0: #ifdef U_DEBUG_CALSVC michael@0: fprintf(stderr, "Done..\n"); michael@0: #endif michael@0: michael@0: if(U_FAILURE(status)) { michael@0: #ifdef U_DEBUG_CALSVC michael@0: fprintf(stderr, "err (%s) registering classes, deleting service.....\n", u_errorName(status)); michael@0: #endif michael@0: delete gService; michael@0: gService = NULL; michael@0: } michael@0: } michael@0: michael@0: static ICULocaleService* michael@0: getCalendarService(UErrorCode &status) michael@0: { michael@0: umtx_initOnce(gServiceInitOnce, &initCalendarService, status); michael@0: return gService; michael@0: } michael@0: michael@0: URegistryKey Calendar::registerFactory(ICUServiceFactory* toAdopt, UErrorCode& status) michael@0: { michael@0: return getCalendarService(status)->registerFactory(toAdopt, status); michael@0: } michael@0: michael@0: UBool Calendar::unregister(URegistryKey key, UErrorCode& status) { michael@0: return getCalendarService(status)->unregister(key, status); michael@0: } michael@0: #endif /* UCONFIG_NO_SERVICE */ michael@0: michael@0: // ------------------------------------- michael@0: michael@0: static const int32_t kCalendarLimits[UCAL_FIELD_COUNT][4] = { michael@0: // Minimum Greatest min Least max Greatest max michael@0: {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // ERA michael@0: {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // YEAR michael@0: {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // MONTH michael@0: {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // WEEK_OF_YEAR michael@0: {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // WEEK_OF_MONTH michael@0: {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_MONTH michael@0: {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_YEAR michael@0: { 1, 1, 7, 7 }, // DAY_OF_WEEK michael@0: {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_WEEK_IN_MONTH michael@0: { 0, 0, 1, 1 }, // AM_PM michael@0: { 0, 0, 11, 11 }, // HOUR michael@0: { 0, 0, 23, 23 }, // HOUR_OF_DAY michael@0: { 0, 0, 59, 59 }, // MINUTE michael@0: { 0, 0, 59, 59 }, // SECOND michael@0: { 0, 0, 999, 999 }, // MILLISECOND michael@0: {-12*kOneHour, -12*kOneHour, 12*kOneHour, 15*kOneHour }, // ZONE_OFFSET michael@0: { 0, 0, 1*kOneHour, 1*kOneHour }, // DST_OFFSET michael@0: {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // YEAR_WOY michael@0: { 1, 1, 7, 7 }, // DOW_LOCAL michael@0: {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // EXTENDED_YEAR michael@0: { -0x7F000000, -0x7F000000, 0x7F000000, 0x7F000000 }, // JULIAN_DAY michael@0: { 0, 0, 24*kOneHour-1, 24*kOneHour-1 }, // MILLISECONDS_IN_DAY michael@0: { 0, 0, 1, 1 }, // IS_LEAP_MONTH michael@0: }; michael@0: michael@0: // Resource bundle tags read by this class michael@0: static const char gMonthNames[] = "monthNames"; michael@0: michael@0: // Data flow in Calendar michael@0: // --------------------- michael@0: michael@0: // The current time is represented in two ways by Calendar: as UTC michael@0: // milliseconds from the epoch start (1 January 1970 0:00 UTC), and as local michael@0: // fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the michael@0: // millis from the fields, and vice versa. The data needed to do this michael@0: // conversion is encapsulated by a TimeZone object owned by the Calendar. michael@0: // The data provided by the TimeZone object may also be overridden if the michael@0: // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class michael@0: // keeps track of what information was most recently set by the caller, and michael@0: // uses that to compute any other information as needed. michael@0: michael@0: // If the user sets the fields using set(), the data flow is as follows. michael@0: // This is implemented by the Calendar subclass's computeTime() method. michael@0: // During this process, certain fields may be ignored. The disambiguation michael@0: // algorithm for resolving which fields to pay attention to is described michael@0: // above. michael@0: michael@0: // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.) michael@0: // | michael@0: // | Using Calendar-specific algorithm michael@0: // V michael@0: // local standard millis michael@0: // | michael@0: // | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET michael@0: // V michael@0: // UTC millis (in time data member) michael@0: michael@0: // If the user sets the UTC millis using setTime(), the data flow is as michael@0: // follows. This is implemented by the Calendar subclass's computeFields() michael@0: // method. michael@0: michael@0: // UTC millis (in time data member) michael@0: // | michael@0: // | Using TimeZone getOffset() michael@0: // V michael@0: // local standard millis michael@0: // | michael@0: // | Using Calendar-specific algorithm michael@0: // V michael@0: // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.) michael@0: michael@0: // In general, a round trip from fields, through local and UTC millis, and michael@0: // back out to fields is made when necessary. This is implemented by the michael@0: // complete() method. Resolving a partial set of fields into a UTC millis michael@0: // value allows all remaining fields to be generated from that value. If michael@0: // the Calendar is lenient, the fields are also renormalized to standard michael@0: // ranges when they are regenerated. michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar::Calendar(UErrorCode& success) michael@0: : UObject(), michael@0: fIsTimeSet(FALSE), michael@0: fAreFieldsSet(FALSE), michael@0: fAreAllFieldsSet(FALSE), michael@0: fAreFieldsVirtuallySet(FALSE), michael@0: fNextStamp((int32_t)kMinimumUserStamp), michael@0: fTime(0), michael@0: fLenient(TRUE), michael@0: fZone(0), michael@0: fRepeatedWallTime(UCAL_WALLTIME_LAST), michael@0: fSkippedWallTime(UCAL_WALLTIME_LAST) michael@0: { michael@0: clear(); michael@0: fZone = TimeZone::createDefault(); michael@0: if (fZone == NULL) { michael@0: success = U_MEMORY_ALLOCATION_ERROR; michael@0: } michael@0: setWeekData(Locale::getDefault(), NULL, success); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar::Calendar(TimeZone* zone, const Locale& aLocale, UErrorCode& success) michael@0: : UObject(), michael@0: fIsTimeSet(FALSE), michael@0: fAreFieldsSet(FALSE), michael@0: fAreAllFieldsSet(FALSE), michael@0: fAreFieldsVirtuallySet(FALSE), michael@0: fNextStamp((int32_t)kMinimumUserStamp), michael@0: fTime(0), michael@0: fLenient(TRUE), michael@0: fZone(0), michael@0: fRepeatedWallTime(UCAL_WALLTIME_LAST), michael@0: fSkippedWallTime(UCAL_WALLTIME_LAST) michael@0: { michael@0: if(zone == 0) { michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d: ILLEGAL ARG because timezone cannot be 0\n", michael@0: __FILE__, __LINE__); michael@0: #endif michael@0: success = U_ILLEGAL_ARGUMENT_ERROR; michael@0: return; michael@0: } michael@0: michael@0: clear(); michael@0: fZone = zone; michael@0: michael@0: setWeekData(aLocale, NULL, success); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar::Calendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& success) michael@0: : UObject(), michael@0: fIsTimeSet(FALSE), michael@0: fAreFieldsSet(FALSE), michael@0: fAreAllFieldsSet(FALSE), michael@0: fAreFieldsVirtuallySet(FALSE), michael@0: fNextStamp((int32_t)kMinimumUserStamp), michael@0: fTime(0), michael@0: fLenient(TRUE), michael@0: fZone(0), michael@0: fRepeatedWallTime(UCAL_WALLTIME_LAST), michael@0: fSkippedWallTime(UCAL_WALLTIME_LAST) michael@0: { michael@0: clear(); michael@0: fZone = zone.clone(); michael@0: if (fZone == NULL) { michael@0: success = U_MEMORY_ALLOCATION_ERROR; michael@0: } michael@0: setWeekData(aLocale, NULL, success); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar::~Calendar() michael@0: { michael@0: delete fZone; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar::Calendar(const Calendar &source) michael@0: : UObject(source) michael@0: { michael@0: fZone = 0; michael@0: *this = source; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar & michael@0: Calendar::operator=(const Calendar &right) michael@0: { michael@0: if (this != &right) { michael@0: uprv_arrayCopy(right.fFields, fFields, UCAL_FIELD_COUNT); michael@0: uprv_arrayCopy(right.fIsSet, fIsSet, UCAL_FIELD_COUNT); michael@0: uprv_arrayCopy(right.fStamp, fStamp, UCAL_FIELD_COUNT); michael@0: fTime = right.fTime; michael@0: fIsTimeSet = right.fIsTimeSet; michael@0: fAreAllFieldsSet = right.fAreAllFieldsSet; michael@0: fAreFieldsSet = right.fAreFieldsSet; michael@0: fAreFieldsVirtuallySet = right.fAreFieldsVirtuallySet; michael@0: fLenient = right.fLenient; michael@0: fRepeatedWallTime = right.fRepeatedWallTime; michael@0: fSkippedWallTime = right.fSkippedWallTime; michael@0: if (fZone != NULL) { michael@0: delete fZone; michael@0: } michael@0: if (right.fZone != NULL) { michael@0: fZone = right.fZone->clone(); michael@0: } michael@0: fFirstDayOfWeek = right.fFirstDayOfWeek; michael@0: fMinimalDaysInFirstWeek = right.fMinimalDaysInFirstWeek; michael@0: fWeekendOnset = right.fWeekendOnset; michael@0: fWeekendOnsetMillis = right.fWeekendOnsetMillis; michael@0: fWeekendCease = right.fWeekendCease; michael@0: fWeekendCeaseMillis = right.fWeekendCeaseMillis; michael@0: fNextStamp = right.fNextStamp; michael@0: uprv_strcpy(validLocale, right.validLocale); michael@0: uprv_strcpy(actualLocale, right.actualLocale); michael@0: } michael@0: michael@0: return *this; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar* U_EXPORT2 michael@0: Calendar::createInstance(UErrorCode& success) michael@0: { michael@0: return createInstance(TimeZone::createDefault(), Locale::getDefault(), success); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar* U_EXPORT2 michael@0: Calendar::createInstance(const TimeZone& zone, UErrorCode& success) michael@0: { michael@0: return createInstance(zone, Locale::getDefault(), success); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar* U_EXPORT2 michael@0: Calendar::createInstance(const Locale& aLocale, UErrorCode& success) michael@0: { michael@0: return createInstance(TimeZone::createDefault(), aLocale, success); michael@0: } michael@0: michael@0: // ------------------------------------- Adopting michael@0: michael@0: // Note: this is the bottleneck that actually calls the service routines. michael@0: michael@0: Calendar* U_EXPORT2 michael@0: Calendar::createInstance(TimeZone* zone, const Locale& aLocale, UErrorCode& success) michael@0: { michael@0: if (U_FAILURE(success)) { michael@0: return NULL; michael@0: } michael@0: michael@0: Locale actualLoc; michael@0: UObject* u = NULL; michael@0: michael@0: #if !UCONFIG_NO_SERVICE michael@0: if (isCalendarServiceUsed()) { michael@0: u = getCalendarService(success)->get(aLocale, LocaleKey::KIND_ANY, &actualLoc, success); michael@0: } michael@0: else michael@0: #endif michael@0: { michael@0: u = createStandardCalendar(getCalendarTypeForLocale(aLocale.getName()), aLocale, success); michael@0: } michael@0: Calendar* c = NULL; michael@0: michael@0: if(U_FAILURE(success) || !u) { michael@0: delete zone; michael@0: if(U_SUCCESS(success)) { // Propagate some kind of err michael@0: success = U_INTERNAL_PROGRAM_ERROR; michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: #if !UCONFIG_NO_SERVICE michael@0: const UnicodeString* str = dynamic_cast(u); michael@0: if(str != NULL) { michael@0: // It's a unicode string telling us what type of calendar to load ("gregorian", etc) michael@0: // Create a Locale over this string michael@0: Locale l(""); michael@0: LocaleUtility::initLocaleFromName(*str, l); michael@0: michael@0: #ifdef U_DEBUG_CALSVC michael@0: fprintf(stderr, "Calendar::createInstance(%s), looking up [%s]\n", aLocale.getName(), l.getName()); michael@0: #endif michael@0: michael@0: Locale actualLoc2; michael@0: delete u; michael@0: u = NULL; michael@0: michael@0: // Don't overwrite actualLoc, since the actual loc from this call michael@0: // may be something like "@calendar=gregorian" -- TODO investigate michael@0: // further... michael@0: c = (Calendar*)getCalendarService(success)->get(l, LocaleKey::KIND_ANY, &actualLoc2, success); michael@0: michael@0: if(U_FAILURE(success) || !c) { michael@0: delete zone; michael@0: if(U_SUCCESS(success)) { michael@0: success = U_INTERNAL_PROGRAM_ERROR; // Propagate some err michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: str = dynamic_cast(c); michael@0: if(str != NULL) { michael@0: // recursed! Second lookup returned a UnicodeString. michael@0: // Perhaps DefaultCalendar{} was set to another locale. michael@0: #ifdef U_DEBUG_CALSVC michael@0: char tmp[200]; michael@0: // Extract a char* out of it.. michael@0: int32_t len = str->length(); michael@0: int32_t actLen = sizeof(tmp)-1; michael@0: if(len > actLen) { michael@0: len = actLen; michael@0: } michael@0: str->extract(0,len,tmp); michael@0: tmp[len]=0; michael@0: michael@0: fprintf(stderr, "err - recursed, 2nd lookup was unistring %s\n", tmp); michael@0: #endif michael@0: success = U_MISSING_RESOURCE_ERROR; // requested a calendar type which could NOT be found. michael@0: delete c; michael@0: delete zone; michael@0: return NULL; michael@0: } michael@0: #ifdef U_DEBUG_CALSVC michael@0: fprintf(stderr, "%p: setting week count data to locale %s, actual locale %s\n", c, (const char*)aLocale.getName(), (const char *)actualLoc.getName()); michael@0: #endif michael@0: c->setWeekData(aLocale, c->getType(), success); // set the correct locale (this was an indirected calendar) michael@0: michael@0: char keyword[ULOC_FULLNAME_CAPACITY]; michael@0: UErrorCode tmpStatus = U_ZERO_ERROR; michael@0: l.getKeywordValue("calendar", keyword, ULOC_FULLNAME_CAPACITY, tmpStatus); michael@0: if (U_SUCCESS(tmpStatus) && uprv_strcmp(keyword, "iso8601") == 0) { michael@0: c->setFirstDayOfWeek(UCAL_MONDAY); michael@0: c->setMinimalDaysInFirstWeek(4); michael@0: } michael@0: } michael@0: else michael@0: #endif /* UCONFIG_NO_SERVICE */ michael@0: { michael@0: // a calendar was returned - we assume the factory did the right thing. michael@0: c = (Calendar*)u; michael@0: } michael@0: michael@0: // Now, reset calendar to default state: michael@0: c->adoptTimeZone(zone); // Set the correct time zone michael@0: c->setTimeInMillis(getNow(), success); // let the new calendar have the current time. michael@0: michael@0: return c; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar* U_EXPORT2 michael@0: Calendar::createInstance(const TimeZone& zone, const Locale& aLocale, UErrorCode& success) michael@0: { michael@0: Calendar* c = createInstance(aLocale, success); michael@0: if(U_SUCCESS(success) && c) { michael@0: c->setTimeZone(zone); michael@0: } michael@0: return c; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: UBool michael@0: Calendar::operator==(const Calendar& that) const michael@0: { michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: return isEquivalentTo(that) && michael@0: getTimeInMillis(status) == that.getTimeInMillis(status) && michael@0: U_SUCCESS(status); michael@0: } michael@0: michael@0: UBool michael@0: Calendar::isEquivalentTo(const Calendar& other) const michael@0: { michael@0: return typeid(*this) == typeid(other) && michael@0: fLenient == other.fLenient && michael@0: fRepeatedWallTime == other.fRepeatedWallTime && michael@0: fSkippedWallTime == other.fSkippedWallTime && michael@0: fFirstDayOfWeek == other.fFirstDayOfWeek && michael@0: fMinimalDaysInFirstWeek == other.fMinimalDaysInFirstWeek && michael@0: fWeekendOnset == other.fWeekendOnset && michael@0: fWeekendOnsetMillis == other.fWeekendOnsetMillis && michael@0: fWeekendCease == other.fWeekendCease && michael@0: fWeekendCeaseMillis == other.fWeekendCeaseMillis && michael@0: *fZone == *other.fZone; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: UBool michael@0: Calendar::equals(const Calendar& when, UErrorCode& status) const michael@0: { michael@0: return (this == &when || michael@0: getTime(status) == when.getTime(status)); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: UBool michael@0: Calendar::before(const Calendar& when, UErrorCode& status) const michael@0: { michael@0: return (this != &when && michael@0: getTimeInMillis(status) < when.getTimeInMillis(status)); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: UBool michael@0: Calendar::after(const Calendar& when, UErrorCode& status) const michael@0: { michael@0: return (this != &when && michael@0: getTimeInMillis(status) > when.getTimeInMillis(status)); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: michael@0: const Locale* U_EXPORT2 michael@0: Calendar::getAvailableLocales(int32_t& count) michael@0: { michael@0: return Locale::getAvailableLocales(count); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: StringEnumeration* U_EXPORT2 michael@0: Calendar::getKeywordValuesForLocale(const char* key, michael@0: const Locale& locale, UBool commonlyUsed, UErrorCode& status) michael@0: { michael@0: // This is a wrapper over ucal_getKeywordValuesForLocale michael@0: UEnumeration *uenum = ucal_getKeywordValuesForLocale(key, locale.getName(), michael@0: commonlyUsed, &status); michael@0: if (U_FAILURE(status)) { michael@0: uenum_close(uenum); michael@0: return NULL; michael@0: } michael@0: return new UStringEnumeration(uenum); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: UDate U_EXPORT2 michael@0: Calendar::getNow() michael@0: { michael@0: return uprv_getUTCtime(); // return as milliseconds michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: /** michael@0: * Gets this Calendar's current time as a long. michael@0: * @return the current time as UTC milliseconds from the epoch. michael@0: */ michael@0: double michael@0: Calendar::getTimeInMillis(UErrorCode& status) const michael@0: { michael@0: if(U_FAILURE(status)) michael@0: return 0.0; michael@0: michael@0: if ( ! fIsTimeSet) michael@0: ((Calendar*)this)->updateTime(status); michael@0: michael@0: /* Test for buffer overflows */ michael@0: if(U_FAILURE(status)) { michael@0: return 0.0; michael@0: } michael@0: return fTime; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: /** michael@0: * Sets this Calendar's current time from the given long value. michael@0: * A status of U_ILLEGAL_ARGUMENT_ERROR is set when millis is michael@0: * outside the range permitted by a Calendar object when not in lenient mode. michael@0: * when in lenient mode the out of range values are pinned to their respective min/max. michael@0: * @param date the new time in UTC milliseconds from the epoch. michael@0: */ michael@0: void michael@0: Calendar::setTimeInMillis( double millis, UErrorCode& status ) { michael@0: if(U_FAILURE(status)) michael@0: return; michael@0: michael@0: if (millis > MAX_MILLIS) { michael@0: if(isLenient()) { michael@0: millis = MAX_MILLIS; michael@0: } else { michael@0: status = U_ILLEGAL_ARGUMENT_ERROR; michael@0: return; michael@0: } michael@0: } else if (millis < MIN_MILLIS) { michael@0: if(isLenient()) { michael@0: millis = MIN_MILLIS; michael@0: } else { michael@0: status = U_ILLEGAL_ARGUMENT_ERROR; michael@0: return; michael@0: } michael@0: } michael@0: michael@0: fTime = millis; michael@0: fAreFieldsSet = fAreAllFieldsSet = FALSE; michael@0: fIsTimeSet = fAreFieldsVirtuallySet = TRUE; michael@0: michael@0: for (int32_t i=0; icomplete(status); // Cast away const michael@0: return U_SUCCESS(status) ? fFields[field] : 0; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::set(UCalendarDateFields field, int32_t value) michael@0: { michael@0: if (fAreFieldsVirtuallySet) { michael@0: UErrorCode ec = U_ZERO_ERROR; michael@0: computeFields(ec); michael@0: } michael@0: fFields[field] = value; michael@0: /* Ensure that the fNextStamp value doesn't go pass max value for int32_t */ michael@0: if (fNextStamp == STAMP_MAX) { michael@0: recalculateStamp(); michael@0: } michael@0: fStamp[field] = fNextStamp++; michael@0: fIsSet[field] = TRUE; // Remove later michael@0: fIsTimeSet = fAreFieldsSet = fAreFieldsVirtuallySet = FALSE; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::set(int32_t year, int32_t month, int32_t date) michael@0: { michael@0: set(UCAL_YEAR, year); michael@0: set(UCAL_MONTH, month); michael@0: set(UCAL_DATE, date); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::set(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute) michael@0: { michael@0: set(UCAL_YEAR, year); michael@0: set(UCAL_MONTH, month); michael@0: set(UCAL_DATE, date); michael@0: set(UCAL_HOUR_OF_DAY, hour); michael@0: set(UCAL_MINUTE, minute); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::set(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second) michael@0: { michael@0: set(UCAL_YEAR, year); michael@0: set(UCAL_MONTH, month); michael@0: set(UCAL_DATE, date); michael@0: set(UCAL_HOUR_OF_DAY, hour); michael@0: set(UCAL_MINUTE, minute); michael@0: set(UCAL_SECOND, second); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::clear() michael@0: { michael@0: for (int32_t i=0; i bestStamp) { michael@0: bestStamp = fStamp[i]; michael@0: } michael@0: } michael@0: return bestStamp; michael@0: } michael@0: michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::complete(UErrorCode& status) michael@0: { michael@0: if (!fIsTimeSet) { michael@0: updateTime(status); michael@0: /* Test for buffer overflows */ michael@0: if(U_FAILURE(status)) { michael@0: return; michael@0: } michael@0: } michael@0: if (!fAreFieldsSet) { michael@0: computeFields(status); // fills in unset fields michael@0: /* Test for buffer overflows */ michael@0: if(U_FAILURE(status)) { michael@0: return; michael@0: } michael@0: fAreFieldsSet = TRUE; michael@0: fAreAllFieldsSet = TRUE; michael@0: } michael@0: } michael@0: michael@0: //------------------------------------------------------------------------- michael@0: // Protected utility methods for use by subclasses. These are very handy michael@0: // for implementing add, roll, and computeFields. michael@0: //------------------------------------------------------------------------- michael@0: michael@0: /** michael@0: * Adjust the specified field so that it is within michael@0: * the allowable range for the date to which this calendar is set. michael@0: * For example, in a Gregorian calendar pinning the {@link #DAY_OF_MONTH DAY_OF_MONTH} michael@0: * field for a calendar set to April 31 would cause it to be set michael@0: * to April 30. michael@0: *

michael@0: * Subclassing: michael@0: *
michael@0: * This utility method is intended for use by subclasses that need to implement michael@0: * their own overrides of {@link #roll roll} and {@link #add add}. michael@0: *

michael@0: * Note: michael@0: * pinField is implemented in terms of michael@0: * {@link #getActualMinimum getActualMinimum} michael@0: * and {@link #getActualMaximum getActualMaximum}. If either of those methods uses michael@0: * a slow, iterative algorithm for a particular field, it would be michael@0: * unwise to attempt to call pinField for that field. If you michael@0: * really do need to do so, you should override this method to do michael@0: * something more efficient for that field. michael@0: *

michael@0: * @param field The calendar field whose value should be pinned. michael@0: * michael@0: * @see #getActualMinimum michael@0: * @see #getActualMaximum michael@0: * @stable ICU 2.0 michael@0: */ michael@0: void Calendar::pinField(UCalendarDateFields field, UErrorCode& status) { michael@0: int32_t max = getActualMaximum(field, status); michael@0: int32_t min = getActualMinimum(field, status); michael@0: michael@0: if (fFields[field] > max) { michael@0: set(field, max); michael@0: } else if (fFields[field] < min) { michael@0: set(field, min); michael@0: } michael@0: } michael@0: michael@0: michael@0: void Calendar::computeFields(UErrorCode &ec) michael@0: { michael@0: if (U_FAILURE(ec)) { michael@0: return; michael@0: } michael@0: // Compute local wall millis michael@0: double localMillis = internalGetTime(); michael@0: int32_t rawOffset, dstOffset; michael@0: getTimeZone().getOffset(localMillis, FALSE, rawOffset, dstOffset, ec); michael@0: localMillis += (rawOffset + dstOffset); michael@0: michael@0: // Mark fields as set. Do this before calling handleComputeFields(). michael@0: uint32_t mask = //fInternalSetMask; michael@0: (1 << UCAL_ERA) | michael@0: (1 << UCAL_YEAR) | michael@0: (1 << UCAL_MONTH) | michael@0: (1 << UCAL_DAY_OF_MONTH) | // = UCAL_DATE michael@0: (1 << UCAL_DAY_OF_YEAR) | michael@0: (1 << UCAL_EXTENDED_YEAR); michael@0: michael@0: for (int32_t i=0; i>= 1; michael@0: } michael@0: michael@0: // We used to check for and correct extreme millis values (near michael@0: // Long.MIN_VALUE or Long.MAX_VALUE) here. Such values would cause michael@0: // overflows from positive to negative (or vice versa) and had to michael@0: // be manually tweaked. We no longer need to do this because we michael@0: // have limited the range of supported dates to those that have a michael@0: // Julian day that fits into an int. This allows us to implement a michael@0: // JULIAN_DAY field and also removes some inelegant code. - Liu michael@0: // 11/6/00 michael@0: michael@0: int32_t days = (int32_t)ClockMath::floorDivide(localMillis, (double)kOneDay); michael@0: michael@0: internalSet(UCAL_JULIAN_DAY,days + kEpochStartAsJulianDay); michael@0: michael@0: #if defined (U_DEBUG_CAL) michael@0: //fprintf(stderr, "%s:%d- Hmm! Jules @ %d, as per %.0lf millis\n", michael@0: //__FILE__, __LINE__, fFields[UCAL_JULIAN_DAY], localMillis); michael@0: #endif michael@0: michael@0: computeGregorianAndDOWFields(fFields[UCAL_JULIAN_DAY], ec); michael@0: michael@0: // Call framework method to have subclass compute its fields. michael@0: // These must include, at a minimum, MONTH, DAY_OF_MONTH, michael@0: // EXTENDED_YEAR, YEAR, DAY_OF_YEAR. This method will call internalSet(), michael@0: // which will update stamp[]. michael@0: handleComputeFields(fFields[UCAL_JULIAN_DAY], ec); michael@0: michael@0: // Compute week-related fields, based on the subclass-computed michael@0: // fields computed by handleComputeFields(). michael@0: computeWeekFields(ec); michael@0: michael@0: // Compute time-related fields. These are indepent of the date and michael@0: // of the subclass algorithm. They depend only on the local zone michael@0: // wall milliseconds in day. michael@0: int32_t millisInDay = (int32_t) (localMillis - (days * kOneDay)); michael@0: fFields[UCAL_MILLISECONDS_IN_DAY] = millisInDay; michael@0: fFields[UCAL_MILLISECOND] = millisInDay % 1000; michael@0: millisInDay /= 1000; michael@0: fFields[UCAL_SECOND] = millisInDay % 60; michael@0: millisInDay /= 60; michael@0: fFields[UCAL_MINUTE] = millisInDay % 60; michael@0: millisInDay /= 60; michael@0: fFields[UCAL_HOUR_OF_DAY] = millisInDay; michael@0: fFields[UCAL_AM_PM] = millisInDay / 12; // Assume AM == 0 michael@0: fFields[UCAL_HOUR] = millisInDay % 12; michael@0: fFields[UCAL_ZONE_OFFSET] = rawOffset; michael@0: fFields[UCAL_DST_OFFSET] = dstOffset; michael@0: } michael@0: michael@0: uint8_t Calendar::julianDayToDayOfWeek(double julian) michael@0: { michael@0: // If julian is negative, then julian%7 will be negative, so we adjust michael@0: // accordingly. We add 1 because Julian day 0 is Monday. michael@0: int8_t dayOfWeek = (int8_t) uprv_fmod(julian + 1, 7); michael@0: michael@0: uint8_t result = (uint8_t)(dayOfWeek + ((dayOfWeek < 0) ? (7+UCAL_SUNDAY ) : UCAL_SUNDAY)); michael@0: return result; michael@0: } michael@0: michael@0: /** michael@0: * Compute the Gregorian calendar year, month, and day of month from michael@0: * the given Julian day. These values are not stored in fields, but in michael@0: * member variables gregorianXxx. Also compute the DAY_OF_WEEK and michael@0: * DOW_LOCAL fields. michael@0: */ michael@0: void Calendar::computeGregorianAndDOWFields(int32_t julianDay, UErrorCode &ec) michael@0: { michael@0: computeGregorianFields(julianDay, ec); michael@0: michael@0: // Compute day of week: JD 0 = Monday michael@0: int32_t dow = julianDayToDayOfWeek(julianDay); michael@0: internalSet(UCAL_DAY_OF_WEEK,dow); michael@0: michael@0: // Calculate 1-based localized day of week michael@0: int32_t dowLocal = dow - getFirstDayOfWeek() + 1; michael@0: if (dowLocal < 1) { michael@0: dowLocal += 7; michael@0: } michael@0: internalSet(UCAL_DOW_LOCAL,dowLocal); michael@0: fFields[UCAL_DOW_LOCAL] = dowLocal; michael@0: } michael@0: michael@0: /** michael@0: * Compute the Gregorian calendar year, month, and day of month from the michael@0: * Julian day. These values are not stored in fields, but in member michael@0: * variables gregorianXxx. They are used for time zone computations and by michael@0: * subclasses that are Gregorian derivatives. Subclasses may call this michael@0: * method to perform a Gregorian calendar millis->fields computation. michael@0: */ michael@0: void Calendar::computeGregorianFields(int32_t julianDay, UErrorCode & /* ec */) { michael@0: int32_t gregorianDayOfWeekUnused; michael@0: Grego::dayToFields(julianDay - kEpochStartAsJulianDay, fGregorianYear, fGregorianMonth, fGregorianDayOfMonth, gregorianDayOfWeekUnused, fGregorianDayOfYear); michael@0: } michael@0: michael@0: /** michael@0: * Compute the fields WEEK_OF_YEAR, YEAR_WOY, WEEK_OF_MONTH, michael@0: * DAY_OF_WEEK_IN_MONTH, and DOW_LOCAL from EXTENDED_YEAR, YEAR, michael@0: * DAY_OF_WEEK, and DAY_OF_YEAR. The latter fields are computed by the michael@0: * subclass based on the calendar system. michael@0: * michael@0: *

The YEAR_WOY field is computed simplistically. It is equal to YEAR michael@0: * most of the time, but at the year boundary it may be adjusted to YEAR-1 michael@0: * or YEAR+1 to reflect the overlap of a week into an adjacent year. In michael@0: * this case, a simple increment or decrement is performed on YEAR, even michael@0: * though this may yield an invalid YEAR value. For instance, if the YEAR michael@0: * is part of a calendar system with an N-year cycle field CYCLE, then michael@0: * incrementing the YEAR may involve incrementing CYCLE and setting YEAR michael@0: * back to 0 or 1. This is not handled by this code, and in fact cannot be michael@0: * simply handled without having subclasses define an entire parallel set of michael@0: * fields for fields larger than or equal to a year. This additional michael@0: * complexity is not warranted, since the intention of the YEAR_WOY field is michael@0: * to support ISO 8601 notation, so it will typically be used with a michael@0: * proleptic Gregorian calendar, which has no field larger than a year. michael@0: */ michael@0: void Calendar::computeWeekFields(UErrorCode &ec) { michael@0: if(U_FAILURE(ec)) { michael@0: return; michael@0: } michael@0: int32_t eyear = fFields[UCAL_EXTENDED_YEAR]; michael@0: int32_t dayOfWeek = fFields[UCAL_DAY_OF_WEEK]; michael@0: int32_t dayOfYear = fFields[UCAL_DAY_OF_YEAR]; michael@0: michael@0: // WEEK_OF_YEAR start michael@0: // Compute the week of the year. For the Gregorian calendar, valid week michael@0: // numbers run from 1 to 52 or 53, depending on the year, the first day michael@0: // of the week, and the minimal days in the first week. For other michael@0: // calendars, the valid range may be different -- it depends on the year michael@0: // length. Days at the start of the year may fall into the last week of michael@0: // the previous year; days at the end of the year may fall into the michael@0: // first week of the next year. ASSUME that the year length is less than michael@0: // 7000 days. michael@0: int32_t yearOfWeekOfYear = eyear; michael@0: int32_t relDow = (dayOfWeek + 7 - getFirstDayOfWeek()) % 7; // 0..6 michael@0: int32_t relDowJan1 = (dayOfWeek - dayOfYear + 7001 - getFirstDayOfWeek()) % 7; // 0..6 michael@0: int32_t woy = (dayOfYear - 1 + relDowJan1) / 7; // 0..53 michael@0: if ((7 - relDowJan1) >= getMinimalDaysInFirstWeek()) { michael@0: ++woy; michael@0: } michael@0: michael@0: // Adjust for weeks at the year end that overlap into the previous or michael@0: // next calendar year. michael@0: if (woy == 0) { michael@0: // We are the last week of the previous year. michael@0: // Check to see if we are in the last week; if so, we need michael@0: // to handle the case in which we are the first week of the michael@0: // next year. michael@0: michael@0: int32_t prevDoy = dayOfYear + handleGetYearLength(eyear - 1); michael@0: woy = weekNumber(prevDoy, dayOfWeek); michael@0: yearOfWeekOfYear--; michael@0: } else { michael@0: int32_t lastDoy = handleGetYearLength(eyear); michael@0: // Fast check: For it to be week 1 of the next year, the DOY michael@0: // must be on or after L-5, where L is yearLength(), then it michael@0: // cannot possibly be week 1 of the next year: michael@0: // L-5 L michael@0: // doy: 359 360 361 362 363 364 365 001 michael@0: // dow: 1 2 3 4 5 6 7 michael@0: if (dayOfYear >= (lastDoy - 5)) { michael@0: int32_t lastRelDow = (relDow + lastDoy - dayOfYear) % 7; michael@0: if (lastRelDow < 0) { michael@0: lastRelDow += 7; michael@0: } michael@0: if (((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) && michael@0: ((dayOfYear + 7 - relDow) > lastDoy)) { michael@0: woy = 1; michael@0: yearOfWeekOfYear++; michael@0: } michael@0: } michael@0: } michael@0: fFields[UCAL_WEEK_OF_YEAR] = woy; michael@0: fFields[UCAL_YEAR_WOY] = yearOfWeekOfYear; michael@0: // WEEK_OF_YEAR end michael@0: michael@0: int32_t dayOfMonth = fFields[UCAL_DAY_OF_MONTH]; michael@0: fFields[UCAL_WEEK_OF_MONTH] = weekNumber(dayOfMonth, dayOfWeek); michael@0: fFields[UCAL_DAY_OF_WEEK_IN_MONTH] = (dayOfMonth-1) / 7 + 1; michael@0: #if defined (U_DEBUG_CAL) michael@0: if(fFields[UCAL_DAY_OF_WEEK_IN_MONTH]==0) fprintf(stderr, "%s:%d: DOWIM %d on %g\n", michael@0: __FILE__, __LINE__,fFields[UCAL_DAY_OF_WEEK_IN_MONTH], fTime); michael@0: #endif michael@0: } michael@0: michael@0: michael@0: int32_t Calendar::weekNumber(int32_t desiredDay, int32_t dayOfPeriod, int32_t dayOfWeek) michael@0: { michael@0: // Determine the day of the week of the first day of the period michael@0: // in question (either a year or a month). Zero represents the michael@0: // first day of the week on this calendar. michael@0: int32_t periodStartDayOfWeek = (dayOfWeek - getFirstDayOfWeek() - dayOfPeriod + 1) % 7; michael@0: if (periodStartDayOfWeek < 0) periodStartDayOfWeek += 7; michael@0: michael@0: // Compute the week number. Initially, ignore the first week, which michael@0: // may be fractional (or may not be). We add periodStartDayOfWeek in michael@0: // order to fill out the first week, if it is fractional. michael@0: int32_t weekNo = (desiredDay + periodStartDayOfWeek - 1)/7; michael@0: michael@0: // If the first week is long enough, then count it. If michael@0: // the minimal days in the first week is one, or if the period start michael@0: // is zero, we always increment weekNo. michael@0: if ((7 - periodStartDayOfWeek) >= getMinimalDaysInFirstWeek()) ++weekNo; michael@0: michael@0: return weekNo; michael@0: } michael@0: michael@0: void Calendar::handleComputeFields(int32_t /* julianDay */, UErrorCode &/* status */) michael@0: { michael@0: internalSet(UCAL_MONTH, getGregorianMonth()); michael@0: internalSet(UCAL_DAY_OF_MONTH, getGregorianDayOfMonth()); michael@0: internalSet(UCAL_DAY_OF_YEAR, getGregorianDayOfYear()); michael@0: int32_t eyear = getGregorianYear(); michael@0: internalSet(UCAL_EXTENDED_YEAR, eyear); michael@0: int32_t era = GregorianCalendar::AD; michael@0: if (eyear < 1) { michael@0: era = GregorianCalendar::BC; michael@0: eyear = 1 - eyear; michael@0: } michael@0: internalSet(UCAL_ERA, era); michael@0: internalSet(UCAL_YEAR, eyear); michael@0: } michael@0: // ------------------------------------- michael@0: michael@0: michael@0: void Calendar::roll(EDateFields field, int32_t amount, UErrorCode& status) michael@0: { michael@0: roll((UCalendarDateFields)field, amount, status); michael@0: } michael@0: michael@0: void Calendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) michael@0: { michael@0: if (amount == 0) { michael@0: return; // Nothing to do michael@0: } michael@0: michael@0: complete(status); michael@0: michael@0: if(U_FAILURE(status)) { michael@0: return; michael@0: } michael@0: switch (field) { michael@0: case UCAL_DAY_OF_MONTH: michael@0: case UCAL_AM_PM: michael@0: case UCAL_MINUTE: michael@0: case UCAL_SECOND: michael@0: case UCAL_MILLISECOND: michael@0: case UCAL_MILLISECONDS_IN_DAY: michael@0: case UCAL_ERA: michael@0: // These are the standard roll instructions. These work for all michael@0: // simple cases, that is, cases in which the limits are fixed, such michael@0: // as the hour, the day of the month, and the era. michael@0: { michael@0: int32_t min = getActualMinimum(field,status); michael@0: int32_t max = getActualMaximum(field,status); michael@0: int32_t gap = max - min + 1; michael@0: michael@0: int32_t value = internalGet(field) + amount; michael@0: value = (value - min) % gap; michael@0: if (value < 0) { michael@0: value += gap; michael@0: } michael@0: value += min; michael@0: michael@0: set(field, value); michael@0: return; michael@0: } michael@0: michael@0: case UCAL_HOUR: michael@0: case UCAL_HOUR_OF_DAY: michael@0: // Rolling the hour is difficult on the ONSET and CEASE days of michael@0: // daylight savings. For example, if the change occurs at michael@0: // 2 AM, we have the following progression: michael@0: // ONSET: 12 Std -> 1 Std -> 3 Dst -> 4 Dst michael@0: // CEASE: 12 Dst -> 1 Dst -> 1 Std -> 2 Std michael@0: // To get around this problem we don't use fields; we manipulate michael@0: // the time in millis directly. michael@0: { michael@0: // Assume min == 0 in calculations below michael@0: double start = getTimeInMillis(status); michael@0: int32_t oldHour = internalGet(field); michael@0: int32_t max = getMaximum(field); michael@0: int32_t newHour = (oldHour + amount) % (max + 1); michael@0: if (newHour < 0) { michael@0: newHour += max + 1; michael@0: } michael@0: setTimeInMillis(start + kOneHour * (newHour - oldHour),status); michael@0: return; michael@0: } michael@0: michael@0: case UCAL_MONTH: michael@0: // Rolling the month involves both pinning the final value michael@0: // and adjusting the DAY_OF_MONTH if necessary. We only adjust the michael@0: // DAY_OF_MONTH if, after updating the MONTH field, it is illegal. michael@0: // E.g., .roll(MONTH, 1) -> or . michael@0: { michael@0: int32_t max = getActualMaximum(UCAL_MONTH, status); michael@0: int32_t mon = (internalGet(UCAL_MONTH) + amount) % (max+1); michael@0: michael@0: if (mon < 0) { michael@0: mon += (max + 1); michael@0: } michael@0: set(UCAL_MONTH, mon); michael@0: michael@0: // Keep the day of month in range. We don't want to spill over michael@0: // into the next month; e.g., we don't want jan31 + 1 mo -> feb31 -> michael@0: // mar3. michael@0: pinField(UCAL_DAY_OF_MONTH,status); michael@0: return; michael@0: } michael@0: michael@0: case UCAL_YEAR: michael@0: case UCAL_YEAR_WOY: michael@0: { michael@0: // * If era==0 and years go backwards in time, change sign of amount. michael@0: // * Until we have new API per #9393, we temporarily hardcode knowledge of michael@0: // which calendars have era 0 years that go backwards. michael@0: UBool era0WithYearsThatGoBackwards = FALSE; michael@0: int32_t era = get(UCAL_ERA, status); michael@0: if (era == 0) { michael@0: const char * calType = getType(); michael@0: if ( uprv_strcmp(calType,"gregorian")==0 || uprv_strcmp(calType,"roc")==0 || uprv_strcmp(calType,"coptic")==0 ) { michael@0: amount = -amount; michael@0: era0WithYearsThatGoBackwards = TRUE; michael@0: } michael@0: } michael@0: int32_t newYear = internalGet(field) + amount; michael@0: if (era > 0 || newYear >= 1) { michael@0: int32_t maxYear = getActualMaximum(field, status); michael@0: if (maxYear < 32768) { michael@0: // this era has real bounds, roll should wrap years michael@0: if (newYear < 1) { michael@0: newYear = maxYear - ((-newYear) % maxYear); michael@0: } else if (newYear > maxYear) { michael@0: newYear = ((newYear - 1) % maxYear) + 1; michael@0: } michael@0: // else era is unbounded, just pin low year instead of wrapping michael@0: } else if (newYear < 1) { michael@0: newYear = 1; michael@0: } michael@0: // else we are in era 0 with newYear < 1; michael@0: // calendars with years that go backwards must pin the year value at 0, michael@0: // other calendars can have years < 0 in era 0 michael@0: } else if (era0WithYearsThatGoBackwards) { michael@0: newYear = 1; michael@0: } michael@0: set(field, newYear); michael@0: pinField(UCAL_MONTH,status); michael@0: pinField(UCAL_DAY_OF_MONTH,status); michael@0: return; michael@0: } michael@0: michael@0: case UCAL_EXTENDED_YEAR: michael@0: // Rolling the year can involve pinning the DAY_OF_MONTH. michael@0: set(field, internalGet(field) + amount); michael@0: pinField(UCAL_MONTH,status); michael@0: pinField(UCAL_DAY_OF_MONTH,status); michael@0: return; michael@0: michael@0: case UCAL_WEEK_OF_MONTH: michael@0: { michael@0: // This is tricky, because during the roll we may have to shift michael@0: // to a different day of the week. For example: michael@0: michael@0: // s m t w r f s michael@0: // 1 2 3 4 5 michael@0: // 6 7 8 9 10 11 12 michael@0: michael@0: // When rolling from the 6th or 7th back one week, we go to the michael@0: // 1st (assuming that the first partial week counts). The same michael@0: // thing happens at the end of the month. michael@0: michael@0: // The other tricky thing is that we have to figure out whether michael@0: // the first partial week actually counts or not, based on the michael@0: // minimal first days in the week. And we have to use the michael@0: // correct first day of the week to delineate the week michael@0: // boundaries. michael@0: michael@0: // Here's our algorithm. First, we find the real boundaries of michael@0: // the month. Then we discard the first partial week if it michael@0: // doesn't count in this locale. Then we fill in the ends with michael@0: // phantom days, so that the first partial week and the last michael@0: // partial week are full weeks. We then have a nice square michael@0: // block of weeks. We do the usual rolling within this block, michael@0: // as is done elsewhere in this method. If we wind up on one of michael@0: // the phantom days that we added, we recognize this and pin to michael@0: // the first or the last day of the month. Easy, eh? michael@0: michael@0: // Normalize the DAY_OF_WEEK so that 0 is the first day of the week michael@0: // in this locale. We have dow in 0..6. michael@0: int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek(); michael@0: if (dow < 0) dow += 7; michael@0: michael@0: // Find the day of the week (normalized for locale) for the first michael@0: // of the month. michael@0: int32_t fdm = (dow - internalGet(UCAL_DAY_OF_MONTH) + 1) % 7; michael@0: if (fdm < 0) fdm += 7; michael@0: michael@0: // Get the first day of the first full week of the month, michael@0: // including phantom days, if any. Figure out if the first week michael@0: // counts or not; if it counts, then fill in phantom days. If michael@0: // not, advance to the first real full week (skip the partial week). michael@0: int32_t start; michael@0: if ((7 - fdm) < getMinimalDaysInFirstWeek()) michael@0: start = 8 - fdm; // Skip the first partial week michael@0: else michael@0: start = 1 - fdm; // This may be zero or negative michael@0: michael@0: // Get the day of the week (normalized for locale) for the last michael@0: // day of the month. michael@0: int32_t monthLen = getActualMaximum(UCAL_DAY_OF_MONTH, status); michael@0: int32_t ldm = (monthLen - internalGet(UCAL_DAY_OF_MONTH) + dow) % 7; michael@0: // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here. michael@0: michael@0: // Get the limit day for the blocked-off rectangular month; that michael@0: // is, the day which is one past the last day of the month, michael@0: // after the month has already been filled in with phantom days michael@0: // to fill out the last week. This day has a normalized DOW of 0. michael@0: int32_t limit = monthLen + 7 - ldm; michael@0: michael@0: // Now roll between start and (limit - 1). michael@0: int32_t gap = limit - start; michael@0: int32_t day_of_month = (internalGet(UCAL_DAY_OF_MONTH) + amount*7 - michael@0: start) % gap; michael@0: if (day_of_month < 0) day_of_month += gap; michael@0: day_of_month += start; michael@0: michael@0: // Finally, pin to the real start and end of the month. michael@0: if (day_of_month < 1) day_of_month = 1; michael@0: if (day_of_month > monthLen) day_of_month = monthLen; michael@0: michael@0: // Set the DAY_OF_MONTH. We rely on the fact that this field michael@0: // takes precedence over everything else (since all other fields michael@0: // are also set at this point). If this fact changes (if the michael@0: // disambiguation algorithm changes) then we will have to unset michael@0: // the appropriate fields here so that DAY_OF_MONTH is attended michael@0: // to. michael@0: set(UCAL_DAY_OF_MONTH, day_of_month); michael@0: return; michael@0: } michael@0: case UCAL_WEEK_OF_YEAR: michael@0: { michael@0: // This follows the outline of WEEK_OF_MONTH, except it applies michael@0: // to the whole year. Please see the comment for WEEK_OF_MONTH michael@0: // for general notes. michael@0: michael@0: // Normalize the DAY_OF_WEEK so that 0 is the first day of the week michael@0: // in this locale. We have dow in 0..6. michael@0: int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek(); michael@0: if (dow < 0) dow += 7; michael@0: michael@0: // Find the day of the week (normalized for locale) for the first michael@0: // of the year. michael@0: int32_t fdy = (dow - internalGet(UCAL_DAY_OF_YEAR) + 1) % 7; michael@0: if (fdy < 0) fdy += 7; michael@0: michael@0: // Get the first day of the first full week of the year, michael@0: // including phantom days, if any. Figure out if the first week michael@0: // counts or not; if it counts, then fill in phantom days. If michael@0: // not, advance to the first real full week (skip the partial week). michael@0: int32_t start; michael@0: if ((7 - fdy) < getMinimalDaysInFirstWeek()) michael@0: start = 8 - fdy; // Skip the first partial week michael@0: else michael@0: start = 1 - fdy; // This may be zero or negative michael@0: michael@0: // Get the day of the week (normalized for locale) for the last michael@0: // day of the year. michael@0: int32_t yearLen = getActualMaximum(UCAL_DAY_OF_YEAR,status); michael@0: int32_t ldy = (yearLen - internalGet(UCAL_DAY_OF_YEAR) + dow) % 7; michael@0: // We know yearLen >= DAY_OF_YEAR so we skip the += 7 step here. michael@0: michael@0: // Get the limit day for the blocked-off rectangular year; that michael@0: // is, the day which is one past the last day of the year, michael@0: // after the year has already been filled in with phantom days michael@0: // to fill out the last week. This day has a normalized DOW of 0. michael@0: int32_t limit = yearLen + 7 - ldy; michael@0: michael@0: // Now roll between start and (limit - 1). michael@0: int32_t gap = limit - start; michael@0: int32_t day_of_year = (internalGet(UCAL_DAY_OF_YEAR) + amount*7 - michael@0: start) % gap; michael@0: if (day_of_year < 0) day_of_year += gap; michael@0: day_of_year += start; michael@0: michael@0: // Finally, pin to the real start and end of the month. michael@0: if (day_of_year < 1) day_of_year = 1; michael@0: if (day_of_year > yearLen) day_of_year = yearLen; michael@0: michael@0: // Make sure that the year and day of year are attended to by michael@0: // clearing other fields which would normally take precedence. michael@0: // If the disambiguation algorithm is changed, this section will michael@0: // have to be updated as well. michael@0: set(UCAL_DAY_OF_YEAR, day_of_year); michael@0: clear(UCAL_MONTH); michael@0: return; michael@0: } michael@0: case UCAL_DAY_OF_YEAR: michael@0: { michael@0: // Roll the day of year using millis. Compute the millis for michael@0: // the start of the year, and get the length of the year. michael@0: double delta = amount * kOneDay; // Scale up from days to millis michael@0: double min2 = internalGet(UCAL_DAY_OF_YEAR)-1; michael@0: min2 *= kOneDay; michael@0: min2 = internalGetTime() - min2; michael@0: michael@0: // double min2 = internalGetTime() - (internalGet(UCAL_DAY_OF_YEAR) - 1.0) * kOneDay; michael@0: double newtime; michael@0: michael@0: double yearLength = getActualMaximum(UCAL_DAY_OF_YEAR,status); michael@0: double oneYear = yearLength; michael@0: oneYear *= kOneDay; michael@0: newtime = uprv_fmod((internalGetTime() + delta - min2), oneYear); michael@0: if (newtime < 0) newtime += oneYear; michael@0: setTimeInMillis(newtime + min2, status); michael@0: return; michael@0: } michael@0: case UCAL_DAY_OF_WEEK: michael@0: case UCAL_DOW_LOCAL: michael@0: { michael@0: // Roll the day of week using millis. Compute the millis for michael@0: // the start of the week, using the first day of week setting. michael@0: // Restrict the millis to [start, start+7days). michael@0: double delta = amount * kOneDay; // Scale up from days to millis michael@0: // Compute the number of days before the current day in this michael@0: // week. This will be a value 0..6. michael@0: int32_t leadDays = internalGet(field); michael@0: leadDays -= (field == UCAL_DAY_OF_WEEK) ? getFirstDayOfWeek() : 1; michael@0: if (leadDays < 0) leadDays += 7; michael@0: double min2 = internalGetTime() - leadDays * kOneDay; michael@0: double newtime = uprv_fmod((internalGetTime() + delta - min2), kOneWeek); michael@0: if (newtime < 0) newtime += kOneWeek; michael@0: setTimeInMillis(newtime + min2, status); michael@0: return; michael@0: } michael@0: case UCAL_DAY_OF_WEEK_IN_MONTH: michael@0: { michael@0: // Roll the day of week in the month using millis. Determine michael@0: // the first day of the week in the month, and then the last, michael@0: // and then roll within that range. michael@0: double delta = amount * kOneWeek; // Scale up from weeks to millis michael@0: // Find the number of same days of the week before this one michael@0: // in this month. michael@0: int32_t preWeeks = (internalGet(UCAL_DAY_OF_MONTH) - 1) / 7; michael@0: // Find the number of same days of the week after this one michael@0: // in this month. michael@0: int32_t postWeeks = (getActualMaximum(UCAL_DAY_OF_MONTH,status) - michael@0: internalGet(UCAL_DAY_OF_MONTH)) / 7; michael@0: // From these compute the min and gap millis for rolling. michael@0: double min2 = internalGetTime() - preWeeks * kOneWeek; michael@0: double gap2 = kOneWeek * (preWeeks + postWeeks + 1); // Must add 1! michael@0: // Roll within this range michael@0: double newtime = uprv_fmod((internalGetTime() + delta - min2), gap2); michael@0: if (newtime < 0) newtime += gap2; michael@0: setTimeInMillis(newtime + min2, status); michael@0: return; michael@0: } michael@0: case UCAL_JULIAN_DAY: michael@0: set(field, internalGet(field) + amount); michael@0: return; michael@0: default: michael@0: // Other fields cannot be rolled by this method michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d: ILLEGAL ARG because of roll on non-rollable field %s\n", michael@0: __FILE__, __LINE__,fldName(field)); michael@0: #endif michael@0: status = U_ILLEGAL_ARGUMENT_ERROR; michael@0: } michael@0: } michael@0: michael@0: void Calendar::add(EDateFields field, int32_t amount, UErrorCode& status) michael@0: { michael@0: Calendar::add((UCalendarDateFields)field, amount, status); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: void Calendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& status) michael@0: { michael@0: if (amount == 0) { michael@0: return; // Do nothing! michael@0: } michael@0: michael@0: // We handle most fields in the same way. The algorithm is to add michael@0: // a computed amount of millis to the current millis. The only michael@0: // wrinkle is with DST (and/or a change to the zone's UTC offset, which michael@0: // we'll include with DST) -- for some fields, like the DAY_OF_MONTH, michael@0: // we don't want the HOUR to shift due to changes in DST. If the michael@0: // result of the add operation is to move from DST to Standard, or michael@0: // vice versa, we need to adjust by an hour forward or back, michael@0: // respectively. For such fields we set keepHourInvariant to TRUE. michael@0: michael@0: // We only adjust the DST for fields larger than an hour. For michael@0: // fields smaller than an hour, we cannot adjust for DST without michael@0: // causing problems. for instance, if you add one hour to April 5, michael@0: // 1998, 1:00 AM, in PST, the time becomes "2:00 AM PDT" (an michael@0: // illegal value), but then the adjustment sees the change and michael@0: // compensates by subtracting an hour. As a result the time michael@0: // doesn't advance at all. michael@0: michael@0: // For some fields larger than a day, such as a UCAL_MONTH, we pin the michael@0: // UCAL_DAY_OF_MONTH. This allows .add(UCAL_MONTH, 1) to be michael@0: // , rather than => . michael@0: michael@0: double delta = amount; // delta in ms michael@0: UBool keepHourInvariant = TRUE; michael@0: michael@0: switch (field) { michael@0: case UCAL_ERA: michael@0: set(field, get(field, status) + amount); michael@0: pinField(UCAL_ERA, status); michael@0: return; michael@0: michael@0: case UCAL_YEAR: michael@0: case UCAL_YEAR_WOY: michael@0: { michael@0: // * If era=0 and years go backwards in time, change sign of amount. michael@0: // * Until we have new API per #9393, we temporarily hardcode knowledge of michael@0: // which calendars have era 0 years that go backwards. michael@0: // * Note that for UCAL_YEAR (but not UCAL_YEAR_WOY) we could instead handle michael@0: // this by applying the amount to the UCAL_EXTENDED_YEAR field; but since michael@0: // we would still need to handle UCAL_YEAR_WOY as below, might as well michael@0: // also handle UCAL_YEAR the same way. michael@0: int32_t era = get(UCAL_ERA, status); michael@0: if (era == 0) { michael@0: const char * calType = getType(); michael@0: if ( uprv_strcmp(calType,"gregorian")==0 || uprv_strcmp(calType,"roc")==0 || uprv_strcmp(calType,"coptic")==0 ) { michael@0: amount = -amount; michael@0: } michael@0: } michael@0: } michael@0: // Fall through into normal handling michael@0: case UCAL_EXTENDED_YEAR: michael@0: case UCAL_MONTH: michael@0: { michael@0: UBool oldLenient = isLenient(); michael@0: setLenient(TRUE); michael@0: set(field, get(field, status) + amount); michael@0: pinField(UCAL_DAY_OF_MONTH, status); michael@0: if(oldLenient==FALSE) { michael@0: complete(status); /* force recalculate */ michael@0: setLenient(oldLenient); michael@0: } michael@0: } michael@0: return; michael@0: michael@0: case UCAL_WEEK_OF_YEAR: michael@0: case UCAL_WEEK_OF_MONTH: michael@0: case UCAL_DAY_OF_WEEK_IN_MONTH: michael@0: delta *= kOneWeek; michael@0: break; michael@0: michael@0: case UCAL_AM_PM: michael@0: delta *= 12 * kOneHour; michael@0: break; michael@0: michael@0: case UCAL_DAY_OF_MONTH: michael@0: case UCAL_DAY_OF_YEAR: michael@0: case UCAL_DAY_OF_WEEK: michael@0: case UCAL_DOW_LOCAL: michael@0: case UCAL_JULIAN_DAY: michael@0: delta *= kOneDay; michael@0: break; michael@0: michael@0: case UCAL_HOUR_OF_DAY: michael@0: case UCAL_HOUR: michael@0: delta *= kOneHour; michael@0: keepHourInvariant = FALSE; michael@0: break; michael@0: michael@0: case UCAL_MINUTE: michael@0: delta *= kOneMinute; michael@0: keepHourInvariant = FALSE; michael@0: break; michael@0: michael@0: case UCAL_SECOND: michael@0: delta *= kOneSecond; michael@0: keepHourInvariant = FALSE; michael@0: break; michael@0: michael@0: case UCAL_MILLISECOND: michael@0: case UCAL_MILLISECONDS_IN_DAY: michael@0: keepHourInvariant = FALSE; michael@0: break; michael@0: michael@0: default: michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d: ILLEGAL ARG because field %s not addable", michael@0: __FILE__, __LINE__, fldName(field)); michael@0: #endif michael@0: status = U_ILLEGAL_ARGUMENT_ERROR; michael@0: return; michael@0: // throw new IllegalArgumentException("Calendar.add(" + fieldName(field) + michael@0: // ") not supported"); michael@0: } michael@0: michael@0: // In order to keep the hour invariant (for fields where this is michael@0: // appropriate), check the combined DST & ZONE offset before and michael@0: // after the add() operation. If it changes, then adjust the millis michael@0: // to compensate. michael@0: int32_t prevOffset = 0; michael@0: int32_t hour = 0; michael@0: if (keepHourInvariant) { michael@0: prevOffset = get(UCAL_DST_OFFSET, status) + get(UCAL_ZONE_OFFSET, status); michael@0: hour = internalGet(UCAL_HOUR_OF_DAY); michael@0: } michael@0: michael@0: setTimeInMillis(getTimeInMillis(status) + delta, status); michael@0: michael@0: if (keepHourInvariant) { michael@0: int32_t newOffset = get(UCAL_DST_OFFSET, status) + get(UCAL_ZONE_OFFSET, status); michael@0: if (newOffset != prevOffset) { michael@0: // We have done an hour-invariant adjustment but the michael@0: // combined offset has changed. We adjust millis to keep michael@0: // the hour constant. In cases such as midnight after michael@0: // a DST change which occurs at midnight, there is the michael@0: // danger of adjusting into a different day. To avoid michael@0: // this we make the adjustment only if it actually michael@0: // maintains the hour. michael@0: michael@0: // When the difference of the previous UTC offset and michael@0: // the new UTC offset exceeds 1 full day, we do not want michael@0: // to roll over/back the date. For now, this only happens michael@0: // in Samoa (Pacific/Apia) on Dec 30, 2011. See ticket:9452. michael@0: int32_t adjAmount = prevOffset - newOffset; michael@0: adjAmount = adjAmount >= 0 ? adjAmount % (int32_t)kOneDay : -(-adjAmount % (int32_t)kOneDay); michael@0: if (adjAmount != 0) { michael@0: double t = internalGetTime(); michael@0: setTimeInMillis(t + adjAmount, status); michael@0: if (get(UCAL_HOUR_OF_DAY, status) != hour) { michael@0: setTimeInMillis(t, status); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: int32_t Calendar::fieldDifference(UDate when, EDateFields field, UErrorCode& status) { michael@0: return fieldDifference(when, (UCalendarDateFields) field, status); michael@0: } michael@0: michael@0: int32_t Calendar::fieldDifference(UDate targetMs, UCalendarDateFields field, UErrorCode& ec) { michael@0: if (U_FAILURE(ec)) return 0; michael@0: int32_t min = 0; michael@0: double startMs = getTimeInMillis(ec); michael@0: // Always add from the start millis. This accomodates michael@0: // operations like adding years from February 29, 2000 up to michael@0: // February 29, 2004. If 1, 1, 1, 1 is added to the year michael@0: // field, the DOM gets pinned to 28 and stays there, giving an michael@0: // incorrect DOM difference of 1. We have to add 1, reset, 2, michael@0: // reset, 3, reset, 4. michael@0: if (startMs < targetMs) { michael@0: int32_t max = 1; michael@0: // Find a value that is too large michael@0: while (U_SUCCESS(ec)) { michael@0: setTimeInMillis(startMs, ec); michael@0: add(field, max, ec); michael@0: double ms = getTimeInMillis(ec); michael@0: if (ms == targetMs) { michael@0: return max; michael@0: } else if (ms > targetMs) { michael@0: break; michael@0: } else if (max < INT32_MAX) { michael@0: min = max; michael@0: max <<= 1; michael@0: if (max < 0) { michael@0: max = INT32_MAX; michael@0: } michael@0: } else { michael@0: // Field difference too large to fit into int32_t michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d: ILLEGAL ARG because field %s's max too large for int32_t\n", michael@0: __FILE__, __LINE__, fldName(field)); michael@0: #endif michael@0: ec = U_ILLEGAL_ARGUMENT_ERROR; michael@0: } michael@0: } michael@0: // Do a binary search michael@0: while ((max - min) > 1 && U_SUCCESS(ec)) { michael@0: int32_t t = min + (max - min)/2; // make sure intermediate values don't exceed INT32_MAX michael@0: setTimeInMillis(startMs, ec); michael@0: add(field, t, ec); michael@0: double ms = getTimeInMillis(ec); michael@0: if (ms == targetMs) { michael@0: return t; michael@0: } else if (ms > targetMs) { michael@0: max = t; michael@0: } else { michael@0: min = t; michael@0: } michael@0: } michael@0: } else if (startMs > targetMs) { michael@0: int32_t max = -1; michael@0: // Find a value that is too small michael@0: while (U_SUCCESS(ec)) { michael@0: setTimeInMillis(startMs, ec); michael@0: add(field, max, ec); michael@0: double ms = getTimeInMillis(ec); michael@0: if (ms == targetMs) { michael@0: return max; michael@0: } else if (ms < targetMs) { michael@0: break; michael@0: } else { michael@0: min = max; michael@0: max <<= 1; michael@0: if (max == 0) { michael@0: // Field difference too large to fit into int32_t michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d: ILLEGAL ARG because field %s's max too large for int32_t\n", michael@0: __FILE__, __LINE__, fldName(field)); michael@0: #endif michael@0: ec = U_ILLEGAL_ARGUMENT_ERROR; michael@0: } michael@0: } michael@0: } michael@0: // Do a binary search michael@0: while ((min - max) > 1 && U_SUCCESS(ec)) { michael@0: int32_t t = min + (max - min)/2; // make sure intermediate values don't exceed INT32_MAX michael@0: setTimeInMillis(startMs, ec); michael@0: add(field, t, ec); michael@0: double ms = getTimeInMillis(ec); michael@0: if (ms == targetMs) { michael@0: return t; michael@0: } else if (ms < targetMs) { michael@0: max = t; michael@0: } else { michael@0: min = t; michael@0: } michael@0: } michael@0: } michael@0: // Set calendar to end point michael@0: setTimeInMillis(startMs, ec); michael@0: add(field, min, ec); michael@0: michael@0: /* Test for buffer overflows */ michael@0: if(U_FAILURE(ec)) { michael@0: return 0; michael@0: } michael@0: return min; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::adoptTimeZone(TimeZone* zone) michael@0: { michael@0: // Do nothing if passed-in zone is NULL michael@0: if (zone == NULL) return; michael@0: michael@0: // fZone should always be non-null michael@0: if (fZone != NULL) delete fZone; michael@0: fZone = zone; michael@0: michael@0: // if the zone changes, we need to recompute the time fields michael@0: fAreFieldsSet = FALSE; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: void michael@0: Calendar::setTimeZone(const TimeZone& zone) michael@0: { michael@0: adoptTimeZone(zone.clone()); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: const TimeZone& michael@0: Calendar::getTimeZone() const michael@0: { michael@0: return *fZone; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: TimeZone* michael@0: Calendar::orphanTimeZone() michael@0: { michael@0: TimeZone *z = fZone; michael@0: // we let go of the time zone; the new time zone is the system default time zone michael@0: fZone = TimeZone::createDefault(); michael@0: return z; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::setLenient(UBool lenient) michael@0: { michael@0: fLenient = lenient; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: UBool michael@0: Calendar::isLenient() const michael@0: { michael@0: return fLenient; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::setRepeatedWallTimeOption(UCalendarWallTimeOption option) michael@0: { michael@0: if (option == UCAL_WALLTIME_LAST || option == UCAL_WALLTIME_FIRST) { michael@0: fRepeatedWallTime = option; michael@0: } michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: UCalendarWallTimeOption michael@0: Calendar::getRepeatedWallTimeOption(void) const michael@0: { michael@0: return fRepeatedWallTime; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::setSkippedWallTimeOption(UCalendarWallTimeOption option) michael@0: { michael@0: fSkippedWallTime = option; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: UCalendarWallTimeOption michael@0: Calendar::getSkippedWallTimeOption(void) const michael@0: { michael@0: return fSkippedWallTime; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::setFirstDayOfWeek(UCalendarDaysOfWeek value) michael@0: { michael@0: if (fFirstDayOfWeek != value && michael@0: value >= UCAL_SUNDAY && value <= UCAL_SATURDAY) { michael@0: fFirstDayOfWeek = value; michael@0: fAreFieldsSet = FALSE; michael@0: } michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: Calendar::EDaysOfWeek michael@0: Calendar::getFirstDayOfWeek() const michael@0: { michael@0: return (Calendar::EDaysOfWeek)fFirstDayOfWeek; michael@0: } michael@0: michael@0: UCalendarDaysOfWeek michael@0: Calendar::getFirstDayOfWeek(UErrorCode & /*status*/) const michael@0: { michael@0: return fFirstDayOfWeek; michael@0: } michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::setMinimalDaysInFirstWeek(uint8_t value) michael@0: { michael@0: // Values less than 1 have the same effect as 1; values greater michael@0: // than 7 have the same effect as 7. However, we normalize values michael@0: // so operator== and so forth work. michael@0: if (value < 1) { michael@0: value = 1; michael@0: } else if (value > 7) { michael@0: value = 7; michael@0: } michael@0: if (fMinimalDaysInFirstWeek != value) { michael@0: fMinimalDaysInFirstWeek = value; michael@0: fAreFieldsSet = FALSE; michael@0: } michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: uint8_t michael@0: Calendar::getMinimalDaysInFirstWeek() const michael@0: { michael@0: return fMinimalDaysInFirstWeek; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: // weekend functions, just dummy implementations for now (for API freeze) michael@0: michael@0: UCalendarWeekdayType michael@0: Calendar::getDayOfWeekType(UCalendarDaysOfWeek dayOfWeek, UErrorCode &status) const michael@0: { michael@0: if (U_FAILURE(status)) { michael@0: return UCAL_WEEKDAY; michael@0: } michael@0: if (dayOfWeek < UCAL_SUNDAY || dayOfWeek > UCAL_SATURDAY) { michael@0: status = U_ILLEGAL_ARGUMENT_ERROR; michael@0: return UCAL_WEEKDAY; michael@0: } michael@0: if (fWeekendOnset == fWeekendCease) { michael@0: if (dayOfWeek != fWeekendOnset) michael@0: return UCAL_WEEKDAY; michael@0: return (fWeekendOnsetMillis == 0) ? UCAL_WEEKEND : UCAL_WEEKEND_ONSET; michael@0: } michael@0: if (fWeekendOnset < fWeekendCease) { michael@0: if (dayOfWeek < fWeekendOnset || dayOfWeek > fWeekendCease) { michael@0: return UCAL_WEEKDAY; michael@0: } michael@0: } else { michael@0: if (dayOfWeek > fWeekendCease && dayOfWeek < fWeekendOnset) { michael@0: return UCAL_WEEKDAY; michael@0: } michael@0: } michael@0: if (dayOfWeek == fWeekendOnset) { michael@0: return (fWeekendOnsetMillis == 0) ? UCAL_WEEKEND : UCAL_WEEKEND_ONSET; michael@0: } michael@0: if (dayOfWeek == fWeekendCease) { michael@0: return (fWeekendCeaseMillis >= 86400000) ? UCAL_WEEKEND : UCAL_WEEKEND_CEASE; michael@0: } michael@0: return UCAL_WEEKEND; michael@0: } michael@0: michael@0: int32_t michael@0: Calendar::getWeekendTransition(UCalendarDaysOfWeek dayOfWeek, UErrorCode &status) const michael@0: { michael@0: if (U_FAILURE(status)) { michael@0: return 0; michael@0: } michael@0: if (dayOfWeek == fWeekendOnset) { michael@0: return fWeekendOnsetMillis; michael@0: } else if (dayOfWeek == fWeekendCease) { michael@0: return fWeekendCeaseMillis; michael@0: } michael@0: status = U_ILLEGAL_ARGUMENT_ERROR; michael@0: return 0; michael@0: } michael@0: michael@0: UBool michael@0: Calendar::isWeekend(UDate date, UErrorCode &status) const michael@0: { michael@0: if (U_FAILURE(status)) { michael@0: return FALSE; michael@0: } michael@0: // clone the calendar so we don't mess with the real one. michael@0: Calendar *work = (Calendar*)this->clone(); michael@0: if (work == NULL) { michael@0: status = U_MEMORY_ALLOCATION_ERROR; michael@0: return FALSE; michael@0: } michael@0: UBool result = FALSE; michael@0: work->setTime(date, status); michael@0: if (U_SUCCESS(status)) { michael@0: result = work->isWeekend(); michael@0: } michael@0: delete work; michael@0: return result; michael@0: } michael@0: michael@0: UBool michael@0: Calendar::isWeekend(void) const michael@0: { michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: UCalendarDaysOfWeek dayOfWeek = (UCalendarDaysOfWeek)get(UCAL_DAY_OF_WEEK, status); michael@0: UCalendarWeekdayType dayType = getDayOfWeekType(dayOfWeek, status); michael@0: if (U_SUCCESS(status)) { michael@0: switch (dayType) { michael@0: case UCAL_WEEKDAY: michael@0: return FALSE; michael@0: case UCAL_WEEKEND: michael@0: return TRUE; michael@0: case UCAL_WEEKEND_ONSET: michael@0: case UCAL_WEEKEND_CEASE: michael@0: // Use internalGet() because the above call to get() populated all fields. michael@0: { michael@0: int32_t millisInDay = internalGet(UCAL_MILLISECONDS_IN_DAY); michael@0: int32_t transitionMillis = getWeekendTransition(dayOfWeek, status); michael@0: if (U_SUCCESS(status)) { michael@0: return (dayType == UCAL_WEEKEND_ONSET)? michael@0: (millisInDay >= transitionMillis): michael@0: (millisInDay < transitionMillis); michael@0: } michael@0: // else fall through, return FALSE michael@0: } michael@0: default: michael@0: break; michael@0: } michael@0: } michael@0: return FALSE; michael@0: } michael@0: michael@0: // ------------------------------------- limits michael@0: michael@0: int32_t michael@0: Calendar::getMinimum(EDateFields field) const { michael@0: return getLimit((UCalendarDateFields) field,UCAL_LIMIT_MINIMUM); michael@0: } michael@0: michael@0: int32_t michael@0: Calendar::getMinimum(UCalendarDateFields field) const michael@0: { michael@0: return getLimit(field,UCAL_LIMIT_MINIMUM); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: int32_t michael@0: Calendar::getMaximum(EDateFields field) const michael@0: { michael@0: return getLimit((UCalendarDateFields) field,UCAL_LIMIT_MAXIMUM); michael@0: } michael@0: michael@0: int32_t michael@0: Calendar::getMaximum(UCalendarDateFields field) const michael@0: { michael@0: return getLimit(field,UCAL_LIMIT_MAXIMUM); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: int32_t michael@0: Calendar::getGreatestMinimum(EDateFields field) const michael@0: { michael@0: return getLimit((UCalendarDateFields)field,UCAL_LIMIT_GREATEST_MINIMUM); michael@0: } michael@0: michael@0: int32_t michael@0: Calendar::getGreatestMinimum(UCalendarDateFields field) const michael@0: { michael@0: return getLimit(field,UCAL_LIMIT_GREATEST_MINIMUM); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: int32_t michael@0: Calendar::getLeastMaximum(EDateFields field) const michael@0: { michael@0: return getLimit((UCalendarDateFields) field,UCAL_LIMIT_LEAST_MAXIMUM); michael@0: } michael@0: michael@0: int32_t michael@0: Calendar::getLeastMaximum(UCalendarDateFields field) const michael@0: { michael@0: return getLimit( field,UCAL_LIMIT_LEAST_MAXIMUM); michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: int32_t michael@0: Calendar::getActualMinimum(EDateFields field, UErrorCode& status) const michael@0: { michael@0: return getActualMinimum((UCalendarDateFields) field, status); michael@0: } michael@0: michael@0: int32_t Calendar::getLimit(UCalendarDateFields field, ELimitType limitType) const { michael@0: switch (field) { michael@0: case UCAL_DAY_OF_WEEK: michael@0: case UCAL_AM_PM: michael@0: case UCAL_HOUR: michael@0: case UCAL_HOUR_OF_DAY: michael@0: case UCAL_MINUTE: michael@0: case UCAL_SECOND: michael@0: case UCAL_MILLISECOND: michael@0: case UCAL_ZONE_OFFSET: michael@0: case UCAL_DST_OFFSET: michael@0: case UCAL_DOW_LOCAL: michael@0: case UCAL_JULIAN_DAY: michael@0: case UCAL_MILLISECONDS_IN_DAY: michael@0: case UCAL_IS_LEAP_MONTH: michael@0: return kCalendarLimits[field][limitType]; michael@0: michael@0: case UCAL_WEEK_OF_MONTH: michael@0: { michael@0: int32_t limit; michael@0: if (limitType == UCAL_LIMIT_MINIMUM) { michael@0: limit = getMinimalDaysInFirstWeek() == 1 ? 1 : 0; michael@0: } else if (limitType == UCAL_LIMIT_GREATEST_MINIMUM) { michael@0: limit = 1; michael@0: } else { michael@0: int32_t minDaysInFirst = getMinimalDaysInFirstWeek(); michael@0: int32_t daysInMonth = handleGetLimit(UCAL_DAY_OF_MONTH, limitType); michael@0: if (limitType == UCAL_LIMIT_LEAST_MAXIMUM) { michael@0: limit = (daysInMonth + (7 - minDaysInFirst)) / 7; michael@0: } else { // limitType == UCAL_LIMIT_MAXIMUM michael@0: limit = (daysInMonth + 6 + (7 - minDaysInFirst)) / 7; michael@0: } michael@0: } michael@0: return limit; michael@0: } michael@0: default: michael@0: return handleGetLimit(field, limitType); michael@0: } michael@0: } michael@0: michael@0: michael@0: int32_t michael@0: Calendar::getActualMinimum(UCalendarDateFields field, UErrorCode& status) const michael@0: { michael@0: int32_t fieldValue = getGreatestMinimum(field); michael@0: int32_t endValue = getMinimum(field); michael@0: michael@0: // if we know that the minimum value is always the same, just return it michael@0: if (fieldValue == endValue) { michael@0: return fieldValue; michael@0: } michael@0: michael@0: // clone the calendar so we don't mess with the real one, and set it to michael@0: // accept anything for the field values michael@0: Calendar *work = (Calendar*)this->clone(); michael@0: if (work == NULL) { michael@0: status = U_MEMORY_ALLOCATION_ERROR; michael@0: return 0; michael@0: } michael@0: work->setLenient(TRUE); michael@0: michael@0: // now try each value from getLeastMaximum() to getMaximum() one by one until michael@0: // we get a value that normalizes to another value. The last value that michael@0: // normalizes to itself is the actual minimum for the current date michael@0: int32_t result = fieldValue; michael@0: michael@0: do { michael@0: work->set(field, fieldValue); michael@0: if (work->get(field, status) != fieldValue) { michael@0: break; michael@0: } michael@0: else { michael@0: result = fieldValue; michael@0: fieldValue--; michael@0: } michael@0: } while (fieldValue >= endValue); michael@0: michael@0: delete work; michael@0: michael@0: /* Test for buffer overflows */ michael@0: if(U_FAILURE(status)) { michael@0: return 0; michael@0: } michael@0: return result; michael@0: } michael@0: michael@0: // ------------------------------------- michael@0: michael@0: michael@0: michael@0: /** michael@0: * Ensure that each field is within its valid range by calling {@link michael@0: * #validateField(int)} on each field that has been set. This method michael@0: * should only be called if this calendar is not lenient. michael@0: * @see #isLenient michael@0: * @see #validateField(int) michael@0: */ michael@0: void Calendar::validateFields(UErrorCode &status) { michael@0: for (int32_t field = 0; U_SUCCESS(status) && (field < UCAL_FIELD_COUNT); field++) { michael@0: if (fStamp[field] >= kMinimumUserStamp) { michael@0: validateField((UCalendarDateFields)field, status); michael@0: } michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Validate a single field of this calendar. Subclasses should michael@0: * override this method to validate any calendar-specific fields. michael@0: * Generic fields can be handled by michael@0: * Calendar.validateField(). michael@0: * @see #validateField(int, int, int) michael@0: */ michael@0: void Calendar::validateField(UCalendarDateFields field, UErrorCode &status) { michael@0: int32_t y; michael@0: switch (field) { michael@0: case UCAL_DAY_OF_MONTH: michael@0: y = handleGetExtendedYear(); michael@0: validateField(field, 1, handleGetMonthLength(y, internalGet(UCAL_MONTH)), status); michael@0: break; michael@0: case UCAL_DAY_OF_YEAR: michael@0: y = handleGetExtendedYear(); michael@0: validateField(field, 1, handleGetYearLength(y), status); michael@0: break; michael@0: case UCAL_DAY_OF_WEEK_IN_MONTH: michael@0: if (internalGet(field) == 0) { michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d: ILLEGAL ARG because DOW in month cannot be 0\n", michael@0: __FILE__, __LINE__); michael@0: #endif michael@0: status = U_ILLEGAL_ARGUMENT_ERROR; // "DAY_OF_WEEK_IN_MONTH cannot be zero" michael@0: return; michael@0: } michael@0: validateField(field, getMinimum(field), getMaximum(field), status); michael@0: break; michael@0: default: michael@0: validateField(field, getMinimum(field), getMaximum(field), status); michael@0: break; michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Validate a single field of this calendar given its minimum and michael@0: * maximum allowed value. If the field is out of range, throw a michael@0: * descriptive IllegalArgumentException. Subclasses may michael@0: * use this method in their implementation of {@link michael@0: * #validateField(int)}. michael@0: */ michael@0: void Calendar::validateField(UCalendarDateFields field, int32_t min, int32_t max, UErrorCode& status) michael@0: { michael@0: int32_t value = fFields[field]; michael@0: if (value < min || value > max) { michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d: ILLEGAL ARG because of field %s out of range %d..%d at %d\n", michael@0: __FILE__, __LINE__,fldName(field),min,max,value); michael@0: #endif michael@0: status = U_ILLEGAL_ARGUMENT_ERROR; michael@0: return; michael@0: } michael@0: } michael@0: michael@0: // ------------------------- michael@0: michael@0: const UFieldResolutionTable* Calendar::getFieldResolutionTable() const { michael@0: return kDatePrecedence; michael@0: } michael@0: michael@0: michael@0: UCalendarDateFields Calendar::newerField(UCalendarDateFields defaultField, UCalendarDateFields alternateField) const michael@0: { michael@0: if (fStamp[alternateField] > fStamp[defaultField]) { michael@0: return alternateField; michael@0: } michael@0: return defaultField; michael@0: } michael@0: michael@0: UCalendarDateFields Calendar::resolveFields(const UFieldResolutionTable* precedenceTable) { michael@0: int32_t bestField = UCAL_FIELD_COUNT; michael@0: int32_t tempBestField; michael@0: for (int32_t g=0; precedenceTable[g][0][0] != -1 && (bestField == UCAL_FIELD_COUNT); ++g) { michael@0: int32_t bestStamp = kUnset; michael@0: for (int32_t l=0; precedenceTable[g][l][0] != -1; ++l) { michael@0: int32_t lineStamp = kUnset; michael@0: // Skip over first entry if it is negative michael@0: for (int32_t i=((precedenceTable[g][l][0]>=kResolveRemap)?1:0); precedenceTable[g][l][i]!=-1; ++i) { michael@0: U_ASSERT(precedenceTable[g][l][i] < UCAL_FIELD_COUNT); michael@0: int32_t s = fStamp[precedenceTable[g][l][i]]; michael@0: // If any field is unset then don't use this line michael@0: if (s == kUnset) { michael@0: goto linesInGroup; michael@0: } else if(s > lineStamp) { michael@0: lineStamp = s; michael@0: } michael@0: } michael@0: // Record new maximum stamp & field no. michael@0: if (lineStamp > bestStamp) { michael@0: tempBestField = precedenceTable[g][l][0]; // First field refers to entire line michael@0: if (tempBestField >= kResolveRemap) { michael@0: tempBestField &= (kResolveRemap-1); michael@0: // This check is needed to resolve some issues with UCAL_YEAR precedence mapping michael@0: if (tempBestField != UCAL_DATE || (fStamp[UCAL_WEEK_OF_MONTH] < fStamp[tempBestField])) { michael@0: bestField = tempBestField; michael@0: } michael@0: } else { michael@0: bestField = tempBestField; michael@0: } michael@0: michael@0: if (bestField == tempBestField) { michael@0: bestStamp = lineStamp; michael@0: } michael@0: } michael@0: linesInGroup: michael@0: ; michael@0: } michael@0: } michael@0: return (UCalendarDateFields)bestField; michael@0: } michael@0: michael@0: const UFieldResolutionTable Calendar::kDatePrecedence[] = michael@0: { michael@0: { michael@0: { UCAL_DAY_OF_MONTH, kResolveSTOP }, michael@0: { UCAL_WEEK_OF_YEAR, UCAL_DAY_OF_WEEK, kResolveSTOP }, michael@0: { UCAL_WEEK_OF_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP }, michael@0: { UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP }, michael@0: { UCAL_WEEK_OF_YEAR, UCAL_DOW_LOCAL, kResolveSTOP }, michael@0: { UCAL_WEEK_OF_MONTH, UCAL_DOW_LOCAL, kResolveSTOP }, michael@0: { UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP }, michael@0: { UCAL_DAY_OF_YEAR, kResolveSTOP }, michael@0: { kResolveRemap | UCAL_DAY_OF_MONTH, UCAL_YEAR, kResolveSTOP }, // if YEAR is set over YEAR_WOY use DAY_OF_MONTH michael@0: { kResolveRemap | UCAL_WEEK_OF_YEAR, UCAL_YEAR_WOY, kResolveSTOP }, // if YEAR_WOY is set, calc based on WEEK_OF_YEAR michael@0: { kResolveSTOP } michael@0: }, michael@0: { michael@0: { UCAL_WEEK_OF_YEAR, kResolveSTOP }, michael@0: { UCAL_WEEK_OF_MONTH, kResolveSTOP }, michael@0: { UCAL_DAY_OF_WEEK_IN_MONTH, kResolveSTOP }, michael@0: { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP }, michael@0: { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP }, michael@0: { kResolveSTOP } michael@0: }, michael@0: {{kResolveSTOP}} michael@0: }; michael@0: michael@0: michael@0: const UFieldResolutionTable Calendar::kDOWPrecedence[] = michael@0: { michael@0: { michael@0: { UCAL_DAY_OF_WEEK,kResolveSTOP, kResolveSTOP }, michael@0: { UCAL_DOW_LOCAL,kResolveSTOP, kResolveSTOP }, michael@0: {kResolveSTOP} michael@0: }, michael@0: {{kResolveSTOP}} michael@0: }; michael@0: michael@0: // precedence for calculating a year michael@0: const UFieldResolutionTable Calendar::kYearPrecedence[] = michael@0: { michael@0: { michael@0: { UCAL_YEAR, kResolveSTOP }, michael@0: { UCAL_EXTENDED_YEAR, kResolveSTOP }, michael@0: { UCAL_YEAR_WOY, UCAL_WEEK_OF_YEAR, kResolveSTOP }, // YEAR_WOY is useless without WEEK_OF_YEAR michael@0: { kResolveSTOP } michael@0: }, michael@0: {{kResolveSTOP}} michael@0: }; michael@0: michael@0: michael@0: // ------------------------- michael@0: michael@0: michael@0: void Calendar::computeTime(UErrorCode& status) { michael@0: if (!isLenient()) { michael@0: validateFields(status); michael@0: if (U_FAILURE(status)) { michael@0: return; michael@0: } michael@0: } michael@0: michael@0: // Compute the Julian day michael@0: int32_t julianDay = computeJulianDay(); michael@0: michael@0: double millis = Grego::julianDayToMillis(julianDay); michael@0: michael@0: #if defined (U_DEBUG_CAL) michael@0: // int32_t julianInsanityCheck = (int32_t)ClockMath::floorDivide(millis, kOneDay); michael@0: // julianInsanityCheck += kEpochStartAsJulianDay; michael@0: // if(1 || julianInsanityCheck != julianDay) { michael@0: // fprintf(stderr, "%s:%d- D'oh- computed jules %d, to mills (%s)%.lf, recomputed %d\n", michael@0: // __FILE__, __LINE__, julianDay, millis<0.0?"NEG":"", millis, julianInsanityCheck); michael@0: // } michael@0: #endif michael@0: michael@0: int32_t millisInDay; michael@0: michael@0: // We only use MILLISECONDS_IN_DAY if it has been set by the user. michael@0: // This makes it possible for the caller to set the calendar to a michael@0: // time and call clear(MONTH) to reset the MONTH to January. This michael@0: // is legacy behavior. Without this, clear(MONTH) has no effect, michael@0: // since the internally set JULIAN_DAY is used. michael@0: if (fStamp[UCAL_MILLISECONDS_IN_DAY] >= ((int32_t)kMinimumUserStamp) && michael@0: newestStamp(UCAL_AM_PM, UCAL_MILLISECOND, kUnset) <= fStamp[UCAL_MILLISECONDS_IN_DAY]) { michael@0: millisInDay = internalGet(UCAL_MILLISECONDS_IN_DAY); michael@0: } else { michael@0: millisInDay = computeMillisInDay(); michael@0: } michael@0: michael@0: UDate t = 0; michael@0: if (fStamp[UCAL_ZONE_OFFSET] >= ((int32_t)kMinimumUserStamp) || fStamp[UCAL_DST_OFFSET] >= ((int32_t)kMinimumUserStamp)) { michael@0: t = millis + millisInDay - (internalGet(UCAL_ZONE_OFFSET) + internalGet(UCAL_DST_OFFSET)); michael@0: } else { michael@0: // Compute the time zone offset and DST offset. There are two potential michael@0: // ambiguities here. We'll assume a 2:00 am (wall time) switchover time michael@0: // for discussion purposes here. michael@0: // michael@0: // 1. The positive offset change such as transition into DST. michael@0: // Here, a designated time of 2:00 am - 2:59 am does not actually exist. michael@0: // For this case, skippedWallTime option specifies the behavior. michael@0: // For example, 2:30 am is interpreted as; michael@0: // - WALLTIME_LAST(default): 3:30 am (DST) (interpreting 2:30 am as 31 minutes after 1:59 am (STD)) michael@0: // - WALLTIME_FIRST: 1:30 am (STD) (interpreting 2:30 am as 30 minutes before 3:00 am (DST)) michael@0: // - WALLTIME_NEXT_VALID: 3:00 am (DST) (next valid time after 2:30 am on a wall clock) michael@0: // 2. The negative offset change such as transition out of DST. michael@0: // Here, a designated time of 1:00 am - 1:59 am can be in standard or DST. Both are valid michael@0: // representations (the rep jumps from 1:59:59 DST to 1:00:00 Std). michael@0: // For this case, repeatedWallTime option specifies the behavior. michael@0: // For example, 1:30 am is interpreted as; michael@0: // - WALLTIME_LAST(default): 1:30 am (STD) - latter occurrence michael@0: // - WALLTIME_FIRST: 1:30 am (DST) - former occurrence michael@0: // michael@0: // In addition to above, when calendar is strict (not default), wall time falls into michael@0: // the skipped time range will be processed as an error case. michael@0: // michael@0: // These special cases are mostly handled in #computeZoneOffset(long), except WALLTIME_NEXT_VALID michael@0: // at positive offset change. The protected method computeZoneOffset(long) is exposed to Calendar michael@0: // subclass implementations and marked as @stable. Strictly speaking, WALLTIME_NEXT_VALID michael@0: // should be also handled in the same place, but we cannot change the code flow without deprecating michael@0: // the protected method. michael@0: // michael@0: // We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET michael@0: // or DST_OFFSET fields; then we use those fields. michael@0: michael@0: if (!isLenient() || fSkippedWallTime == UCAL_WALLTIME_NEXT_VALID) { michael@0: // When strict, invalidate a wall time falls into a skipped wall time range. michael@0: // When lenient and skipped wall time option is WALLTIME_NEXT_VALID, michael@0: // the result time will be adjusted to the next valid time (on wall clock). michael@0: int32_t zoneOffset = computeZoneOffset(millis, millisInDay, status); michael@0: UDate tmpTime = millis + millisInDay - zoneOffset; michael@0: michael@0: int32_t raw, dst; michael@0: fZone->getOffset(tmpTime, FALSE, raw, dst, status); michael@0: michael@0: if (U_SUCCESS(status)) { michael@0: // zoneOffset != (raw + dst) only when the given wall time fall into michael@0: // a skipped wall time range caused by positive zone offset transition. michael@0: if (zoneOffset != (raw + dst)) { michael@0: if (!isLenient()) { michael@0: status = U_ILLEGAL_ARGUMENT_ERROR; michael@0: } else { michael@0: U_ASSERT(fSkippedWallTime == UCAL_WALLTIME_NEXT_VALID); michael@0: // Adjust time to the next valid wall clock time. michael@0: // At this point, tmpTime is on or after the zone offset transition causing michael@0: // the skipped time range. michael@0: michael@0: BasicTimeZone *btz = getBasicTimeZone(); michael@0: if (btz) { michael@0: TimeZoneTransition transition; michael@0: UBool hasTransition = btz->getPreviousTransition(tmpTime, TRUE, transition); michael@0: if (hasTransition) { michael@0: t = transition.getTime(); michael@0: } else { michael@0: // Could not find any transitions. michael@0: // Note: This should never happen. michael@0: status = U_INTERNAL_PROGRAM_ERROR; michael@0: } michael@0: } else { michael@0: // If not BasicTimeZone, return unsupported error for now. michael@0: // TODO: We may support non-BasicTimeZone in future. michael@0: status = U_UNSUPPORTED_ERROR; michael@0: } michael@0: } michael@0: } else { michael@0: t = tmpTime; michael@0: } michael@0: } michael@0: } else { michael@0: t = millis + millisInDay - computeZoneOffset(millis, millisInDay, status); michael@0: } michael@0: } michael@0: if (U_SUCCESS(status)) { michael@0: internalSetTime(t); michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Compute the milliseconds in the day from the fields. This is a michael@0: * value from 0 to 23:59:59.999 inclusive, unless fields are out of michael@0: * range, in which case it can be an arbitrary value. This value michael@0: * reflects local zone wall time. michael@0: * @stable ICU 2.0 michael@0: */ michael@0: int32_t Calendar::computeMillisInDay() { michael@0: // Do the time portion of the conversion. michael@0: michael@0: int32_t millisInDay = 0; michael@0: michael@0: // Find the best set of fields specifying the time of day. There michael@0: // are only two possibilities here; the HOUR_OF_DAY or the michael@0: // AM_PM and the HOUR. michael@0: int32_t hourOfDayStamp = fStamp[UCAL_HOUR_OF_DAY]; michael@0: int32_t hourStamp = (fStamp[UCAL_HOUR] > fStamp[UCAL_AM_PM])?fStamp[UCAL_HOUR]:fStamp[UCAL_AM_PM]; michael@0: int32_t bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp; michael@0: michael@0: // Hours michael@0: if (bestStamp != kUnset) { michael@0: if (bestStamp == hourOfDayStamp) { michael@0: // Don't normalize here; let overflow bump into the next period. michael@0: // This is consistent with how we handle other fields. michael@0: millisInDay += internalGet(UCAL_HOUR_OF_DAY); michael@0: } else { michael@0: // Don't normalize here; let overflow bump into the next period. michael@0: // This is consistent with how we handle other fields. michael@0: millisInDay += internalGet(UCAL_HOUR); michael@0: millisInDay += 12 * internalGet(UCAL_AM_PM); // Default works for unset AM_PM michael@0: } michael@0: } michael@0: michael@0: // We use the fact that unset == 0; we start with millisInDay michael@0: // == HOUR_OF_DAY. michael@0: millisInDay *= 60; michael@0: millisInDay += internalGet(UCAL_MINUTE); // now have minutes michael@0: millisInDay *= 60; michael@0: millisInDay += internalGet(UCAL_SECOND); // now have seconds michael@0: millisInDay *= 1000; michael@0: millisInDay += internalGet(UCAL_MILLISECOND); // now have millis michael@0: michael@0: return millisInDay; michael@0: } michael@0: michael@0: /** michael@0: * This method can assume EXTENDED_YEAR has been set. michael@0: * @param millis milliseconds of the date fields michael@0: * @param millisInDay milliseconds of the time fields; may be out michael@0: * or range. michael@0: * @stable ICU 2.0 michael@0: */ michael@0: int32_t Calendar::computeZoneOffset(double millis, int32_t millisInDay, UErrorCode &ec) { michael@0: int32_t rawOffset, dstOffset; michael@0: UDate wall = millis + millisInDay; michael@0: BasicTimeZone* btz = getBasicTimeZone(); michael@0: if (btz) { michael@0: int duplicatedTimeOpt = (fRepeatedWallTime == UCAL_WALLTIME_FIRST) ? BasicTimeZone::kFormer : BasicTimeZone::kLatter; michael@0: int nonExistingTimeOpt = (fSkippedWallTime == UCAL_WALLTIME_FIRST) ? BasicTimeZone::kLatter : BasicTimeZone::kFormer; michael@0: btz->getOffsetFromLocal(wall, nonExistingTimeOpt, duplicatedTimeOpt, rawOffset, dstOffset, ec); michael@0: } else { michael@0: const TimeZone& tz = getTimeZone(); michael@0: // By default, TimeZone::getOffset behaves UCAL_WALLTIME_LAST for both. michael@0: tz.getOffset(wall, TRUE, rawOffset, dstOffset, ec); michael@0: michael@0: UBool sawRecentNegativeShift = FALSE; michael@0: if (fRepeatedWallTime == UCAL_WALLTIME_FIRST) { michael@0: // Check if the given wall time falls into repeated time range michael@0: UDate tgmt = wall - (rawOffset + dstOffset); michael@0: michael@0: // Any negative zone transition within last 6 hours? michael@0: // Note: The maximum historic negative zone transition is -3 hours in the tz database. michael@0: // 6 hour window would be sufficient for this purpose. michael@0: int32_t tmpRaw, tmpDst; michael@0: tz.getOffset(tgmt - 6*60*60*1000, FALSE, tmpRaw, tmpDst, ec); michael@0: int32_t offsetDelta = (rawOffset + dstOffset) - (tmpRaw + tmpDst); michael@0: michael@0: U_ASSERT(offsetDelta < -6*60*60*1000); michael@0: if (offsetDelta < 0) { michael@0: sawRecentNegativeShift = TRUE; michael@0: // Negative shift within last 6 hours. When UCAL_WALLTIME_FIRST is used and the given wall time falls michael@0: // into the repeated time range, use offsets before the transition. michael@0: // Note: If it does not fall into the repeated time range, offsets remain unchanged below. michael@0: tz.getOffset(wall + offsetDelta, TRUE, rawOffset, dstOffset, ec); michael@0: } michael@0: } michael@0: if (!sawRecentNegativeShift && fSkippedWallTime == UCAL_WALLTIME_FIRST) { michael@0: // When skipped wall time option is WALLTIME_FIRST, michael@0: // recalculate offsets from the resolved time (non-wall). michael@0: // When the given wall time falls into skipped wall time, michael@0: // the offsets will be based on the zone offsets AFTER michael@0: // the transition (which means, earliest possibe interpretation). michael@0: UDate tgmt = wall - (rawOffset + dstOffset); michael@0: tz.getOffset(tgmt, FALSE, rawOffset, dstOffset, ec); michael@0: } michael@0: } michael@0: return rawOffset + dstOffset; michael@0: } michael@0: michael@0: int32_t Calendar::computeJulianDay() michael@0: { michael@0: // We want to see if any of the date fields is newer than the michael@0: // JULIAN_DAY. If not, then we use JULIAN_DAY. If so, then we do michael@0: // the normal resolution. We only use JULIAN_DAY if it has been michael@0: // set by the user. This makes it possible for the caller to set michael@0: // the calendar to a time and call clear(MONTH) to reset the MONTH michael@0: // to January. This is legacy behavior. Without this, michael@0: // clear(MONTH) has no effect, since the internally set JULIAN_DAY michael@0: // is used. michael@0: if (fStamp[UCAL_JULIAN_DAY] >= (int32_t)kMinimumUserStamp) { michael@0: int32_t bestStamp = newestStamp(UCAL_ERA, UCAL_DAY_OF_WEEK_IN_MONTH, kUnset); michael@0: bestStamp = newestStamp(UCAL_YEAR_WOY, UCAL_EXTENDED_YEAR, bestStamp); michael@0: if (bestStamp <= fStamp[UCAL_JULIAN_DAY]) { michael@0: return internalGet(UCAL_JULIAN_DAY); michael@0: } michael@0: } michael@0: michael@0: UCalendarDateFields bestField = resolveFields(getFieldResolutionTable()); michael@0: if (bestField == UCAL_FIELD_COUNT) { michael@0: bestField = UCAL_DAY_OF_MONTH; michael@0: } michael@0: michael@0: return handleComputeJulianDay(bestField); michael@0: } michael@0: michael@0: // ------------------------------------------- michael@0: michael@0: int32_t Calendar::handleComputeJulianDay(UCalendarDateFields bestField) { michael@0: UBool useMonth = (bestField == UCAL_DAY_OF_MONTH || michael@0: bestField == UCAL_WEEK_OF_MONTH || michael@0: bestField == UCAL_DAY_OF_WEEK_IN_MONTH); michael@0: int32_t year; michael@0: michael@0: if (bestField == UCAL_WEEK_OF_YEAR) { michael@0: year = internalGet(UCAL_YEAR_WOY, handleGetExtendedYear()); michael@0: internalSet(UCAL_EXTENDED_YEAR, year); michael@0: } else { michael@0: year = handleGetExtendedYear(); michael@0: internalSet(UCAL_EXTENDED_YEAR, year); michael@0: } michael@0: michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d: bestField= %s - y=%d\n", __FILE__, __LINE__, fldName(bestField), year); michael@0: #endif michael@0: michael@0: // Get the Julian day of the day BEFORE the start of this year. michael@0: // If useMonth is true, get the day before the start of the month. michael@0: michael@0: // give calendar subclass a chance to have a default 'first' month michael@0: int32_t month; michael@0: michael@0: if(isSet(UCAL_MONTH)) { michael@0: month = internalGet(UCAL_MONTH); michael@0: } else { michael@0: month = getDefaultMonthInYear(year); michael@0: } michael@0: michael@0: int32_t julianDay = handleComputeMonthStart(year, useMonth ? month : 0, useMonth); michael@0: michael@0: if (bestField == UCAL_DAY_OF_MONTH) { michael@0: michael@0: // give calendar subclass a chance to have a default 'first' dom michael@0: int32_t dayOfMonth; michael@0: if(isSet(UCAL_DAY_OF_MONTH)) { michael@0: dayOfMonth = internalGet(UCAL_DAY_OF_MONTH,1); michael@0: } else { michael@0: dayOfMonth = getDefaultDayInMonth(year, month); michael@0: } michael@0: return julianDay + dayOfMonth; michael@0: } michael@0: michael@0: if (bestField == UCAL_DAY_OF_YEAR) { michael@0: return julianDay + internalGet(UCAL_DAY_OF_YEAR); michael@0: } michael@0: michael@0: int32_t firstDayOfWeek = getFirstDayOfWeek(); // Localized fdw michael@0: michael@0: // At this point julianDay is the 0-based day BEFORE the first day of michael@0: // January 1, year 1 of the given calendar. If julianDay == 0, it michael@0: // specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian michael@0: // or Gregorian). (or it is before the month we are in, if useMonth is True) michael@0: michael@0: // At this point we need to process the WEEK_OF_MONTH or michael@0: // WEEK_OF_YEAR, which are similar, or the DAY_OF_WEEK_IN_MONTH. michael@0: // First, perform initial shared computations. These locate the michael@0: // first week of the period. michael@0: michael@0: // Get the 0-based localized DOW of day one of the month or year. michael@0: // Valid range 0..6. michael@0: int32_t first = julianDayToDayOfWeek(julianDay + 1) - firstDayOfWeek; michael@0: if (first < 0) { michael@0: first += 7; michael@0: } michael@0: michael@0: int32_t dowLocal = getLocalDOW(); michael@0: michael@0: // Find the first target DOW (dowLocal) in the month or year. michael@0: // Actually, it may be just before the first of the month or year. michael@0: // It will be an integer from -5..7. michael@0: int32_t date = 1 - first + dowLocal; michael@0: michael@0: if (bestField == UCAL_DAY_OF_WEEK_IN_MONTH) { michael@0: // Adjust the target DOW to be in the month or year. michael@0: if (date < 1) { michael@0: date += 7; michael@0: } michael@0: michael@0: // The only trickiness occurs if the day-of-week-in-month is michael@0: // negative. michael@0: int32_t dim = internalGet(UCAL_DAY_OF_WEEK_IN_MONTH, 1); michael@0: if (dim >= 0) { michael@0: date += 7*(dim - 1); michael@0: michael@0: } else { michael@0: // Move date to the last of this day-of-week in this month, michael@0: // then back up as needed. If dim==-1, we don't back up at michael@0: // all. If dim==-2, we back up once, etc. Don't back up michael@0: // past the first of the given day-of-week in this month. michael@0: // Note that we handle -2, -3, etc. correctly, even though michael@0: // values < -1 are technically disallowed. michael@0: int32_t m = internalGet(UCAL_MONTH, UCAL_JANUARY); michael@0: int32_t monthLength = handleGetMonthLength(year, m); michael@0: date += ((monthLength - date) / 7 + dim + 1) * 7; michael@0: } michael@0: } else { michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d - bf= %s\n", __FILE__, __LINE__, fldName(bestField)); michael@0: #endif michael@0: michael@0: if(bestField == UCAL_WEEK_OF_YEAR) { // ------------------------------------- WOY ------------- michael@0: if(!isSet(UCAL_YEAR_WOY) || // YWOY not set at all or michael@0: ( (resolveFields(kYearPrecedence) != UCAL_YEAR_WOY) // YWOY doesn't have precedence michael@0: && (fStamp[UCAL_YEAR_WOY]!=kInternallySet) ) ) // (excluding where all fields are internally set - then YWOY is used) michael@0: { michael@0: // need to be sure to stay in 'real' year. michael@0: int32_t woy = internalGet(bestField); michael@0: michael@0: int32_t nextJulianDay = handleComputeMonthStart(year+1, 0, FALSE); // jd of day before jan 1 michael@0: int32_t nextFirst = julianDayToDayOfWeek(nextJulianDay + 1) - firstDayOfWeek; michael@0: michael@0: if (nextFirst < 0) { // 0..6 ldow of Jan 1 michael@0: nextFirst += 7; michael@0: } michael@0: michael@0: if(woy==1) { // FIRST WEEK --------------------------------- michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d - woy=%d, yp=%d, nj(%d)=%d, nf=%d", __FILE__, __LINE__, michael@0: internalGet(bestField), resolveFields(kYearPrecedence), year+1, michael@0: nextJulianDay, nextFirst); michael@0: michael@0: fprintf(stderr, " next: %d DFW, min=%d \n", (7-nextFirst), getMinimalDaysInFirstWeek() ); michael@0: #endif michael@0: michael@0: // nextFirst is now the localized DOW of Jan 1 of y-woy+1 michael@0: if((nextFirst > 0) && // Jan 1 starts on FDOW michael@0: (7-nextFirst) >= getMinimalDaysInFirstWeek()) // or enough days in the week michael@0: { michael@0: // Jan 1 of (yearWoy+1) is in yearWoy+1 - recalculate JD to next year michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d - was going to move JD from %d to %d [d%d]\n", __FILE__, __LINE__, michael@0: julianDay, nextJulianDay, (nextJulianDay-julianDay)); michael@0: #endif michael@0: julianDay = nextJulianDay; michael@0: michael@0: // recalculate 'first' [0-based local dow of jan 1] michael@0: first = julianDayToDayOfWeek(julianDay + 1) - firstDayOfWeek; michael@0: if (first < 0) { michael@0: first += 7; michael@0: } michael@0: // recalculate date. michael@0: date = 1 - first + dowLocal; michael@0: } michael@0: } else if(woy>=getLeastMaximum(bestField)) { michael@0: // could be in the last week- find out if this JD would overstep michael@0: int32_t testDate = date; michael@0: if ((7 - first) < getMinimalDaysInFirstWeek()) { michael@0: testDate += 7; michael@0: } michael@0: michael@0: // Now adjust for the week number. michael@0: testDate += 7 * (woy - 1); michael@0: michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d - y=%d, y-1=%d doy%d, njd%d (C.F. %d)\n", michael@0: __FILE__, __LINE__, year, year-1, testDate, julianDay+testDate, nextJulianDay); michael@0: #endif michael@0: if(julianDay+testDate > nextJulianDay) { // is it past Dec 31? (nextJulianDay is day BEFORE year+1's Jan 1) michael@0: // Fire up the calculating engines.. retry YWOY = (year-1) michael@0: julianDay = handleComputeMonthStart(year-1, 0, FALSE); // jd before Jan 1 of previous year michael@0: first = julianDayToDayOfWeek(julianDay + 1) - firstDayOfWeek; // 0 based local dow of first week michael@0: michael@0: if(first < 0) { // 0..6 michael@0: first += 7; michael@0: } michael@0: date = 1 - first + dowLocal; michael@0: michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "%s:%d - date now %d, jd%d, ywoy%d\n", michael@0: __FILE__, __LINE__, date, julianDay, year-1); michael@0: #endif michael@0: michael@0: michael@0: } /* correction needed */ michael@0: } /* leastmaximum */ michael@0: } /* resolvefields(year) != year_woy */ michael@0: } /* bestfield != week_of_year */ michael@0: michael@0: // assert(bestField == WEEK_OF_MONTH || bestField == WEEK_OF_YEAR) michael@0: // Adjust for minimal days in first week michael@0: if ((7 - first) < getMinimalDaysInFirstWeek()) { michael@0: date += 7; michael@0: } michael@0: michael@0: // Now adjust for the week number. michael@0: date += 7 * (internalGet(bestField) - 1); michael@0: } michael@0: michael@0: return julianDay + date; michael@0: } michael@0: michael@0: int32_t michael@0: Calendar::getDefaultMonthInYear(int32_t /*eyear*/) michael@0: { michael@0: return 0; michael@0: } michael@0: michael@0: int32_t michael@0: Calendar::getDefaultDayInMonth(int32_t /*eyear*/, int32_t /*month*/) michael@0: { michael@0: return 1; michael@0: } michael@0: michael@0: michael@0: int32_t Calendar::getLocalDOW() michael@0: { michael@0: // Get zero-based localized DOW, valid range 0..6. This is the DOW michael@0: // we are looking for. michael@0: int32_t dowLocal = 0; michael@0: switch (resolveFields(kDOWPrecedence)) { michael@0: case UCAL_DAY_OF_WEEK: michael@0: dowLocal = internalGet(UCAL_DAY_OF_WEEK) - fFirstDayOfWeek; michael@0: break; michael@0: case UCAL_DOW_LOCAL: michael@0: dowLocal = internalGet(UCAL_DOW_LOCAL) - 1; michael@0: break; michael@0: default: michael@0: break; michael@0: } michael@0: dowLocal = dowLocal % 7; michael@0: if (dowLocal < 0) { michael@0: dowLocal += 7; michael@0: } michael@0: return dowLocal; michael@0: } michael@0: michael@0: int32_t Calendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy) michael@0: { michael@0: // We have UCAL_YEAR_WOY and UCAL_WEEK_OF_YEAR - from those, determine michael@0: // what year we fall in, so that other code can set it properly. michael@0: // (code borrowed from computeWeekFields and handleComputeJulianDay) michael@0: //return yearWoy; michael@0: michael@0: // First, we need a reliable DOW. michael@0: UCalendarDateFields bestField = resolveFields(kDatePrecedence); // !! Note: if subclasses have a different table, they should override handleGetExtendedYearFromWeekFields michael@0: michael@0: // Now, a local DOW michael@0: int32_t dowLocal = getLocalDOW(); // 0..6 michael@0: int32_t firstDayOfWeek = getFirstDayOfWeek(); // Localized fdw michael@0: int32_t jan1Start = handleComputeMonthStart(yearWoy, 0, FALSE); michael@0: int32_t nextJan1Start = handleComputeMonthStart(yearWoy+1, 0, FALSE); // next year's Jan1 start michael@0: michael@0: // At this point julianDay is the 0-based day BEFORE the first day of michael@0: // January 1, year 1 of the given calendar. If julianDay == 0, it michael@0: // specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian michael@0: // or Gregorian). (or it is before the month we are in, if useMonth is True) michael@0: michael@0: // At this point we need to process the WEEK_OF_MONTH or michael@0: // WEEK_OF_YEAR, which are similar, or the DAY_OF_WEEK_IN_MONTH. michael@0: // First, perform initial shared computations. These locate the michael@0: // first week of the period. michael@0: michael@0: // Get the 0-based localized DOW of day one of the month or year. michael@0: // Valid range 0..6. michael@0: int32_t first = julianDayToDayOfWeek(jan1Start + 1) - firstDayOfWeek; michael@0: if (first < 0) { michael@0: first += 7; michael@0: } michael@0: int32_t nextFirst = julianDayToDayOfWeek(nextJan1Start + 1) - firstDayOfWeek; michael@0: if (nextFirst < 0) { michael@0: nextFirst += 7; michael@0: } michael@0: michael@0: int32_t minDays = getMinimalDaysInFirstWeek(); michael@0: UBool jan1InPrevYear = FALSE; // January 1st in the year of WOY is the 1st week? (i.e. first week is < minimal ) michael@0: //UBool nextJan1InPrevYear = FALSE; // January 1st of Year of WOY + 1 is in the first week? michael@0: michael@0: if((7 - first) < minDays) { michael@0: jan1InPrevYear = TRUE; michael@0: } michael@0: michael@0: // if((7 - nextFirst) < minDays) { michael@0: // nextJan1InPrevYear = TRUE; michael@0: // } michael@0: michael@0: switch(bestField) { michael@0: case UCAL_WEEK_OF_YEAR: michael@0: if(woy == 1) { michael@0: if(jan1InPrevYear == TRUE) { michael@0: // the first week of January is in the previous year michael@0: // therefore WOY1 is always solidly within yearWoy michael@0: return yearWoy; michael@0: } else { michael@0: // First WOY is split between two years michael@0: if( dowLocal < first) { // we are prior to Jan 1 michael@0: return yearWoy-1; // previous year michael@0: } else { michael@0: return yearWoy; // in this year michael@0: } michael@0: } michael@0: } else if(woy >= getLeastMaximum(bestField)) { michael@0: // we _might_ be in the last week.. michael@0: int32_t jd = // Calculate JD of our target day: michael@0: jan1Start + // JD of Jan 1 michael@0: (7-first) + // days in the first week (Jan 1.. ) michael@0: (woy-1)*7 + // add the weeks of the year michael@0: dowLocal; // the local dow (0..6) of last week michael@0: if(jan1InPrevYear==FALSE) { michael@0: jd -= 7; // woy already includes Jan 1's week. michael@0: } michael@0: michael@0: if( (jd+1) >= nextJan1Start ) { michael@0: // we are in week 52 or 53 etc. - actual year is yearWoy+1 michael@0: return yearWoy+1; michael@0: } else { michael@0: // still in yearWoy; michael@0: return yearWoy; michael@0: } michael@0: } else { michael@0: // we're not possibly in the last week -must be ywoy michael@0: return yearWoy; michael@0: } michael@0: michael@0: case UCAL_DATE: michael@0: if((internalGet(UCAL_MONTH)==0) && michael@0: (woy >= getLeastMaximum(UCAL_WEEK_OF_YEAR))) { michael@0: return yearWoy+1; // month 0, late woy = in the next year michael@0: } else if(woy==1) { michael@0: //if(nextJan1InPrevYear) { michael@0: if(internalGet(UCAL_MONTH)==0) { michael@0: return yearWoy; michael@0: } else { michael@0: return yearWoy-1; michael@0: } michael@0: //} michael@0: } michael@0: michael@0: //(internalGet(UCAL_DATE) <= (7-first)) /* && in minDow */ ) { michael@0: //within 1st week and in this month.. michael@0: //return yearWoy+1; michael@0: return yearWoy; michael@0: michael@0: default: // assume the year is appropriate michael@0: return yearWoy; michael@0: } michael@0: } michael@0: michael@0: int32_t Calendar::handleGetMonthLength(int32_t extendedYear, int32_t month) const michael@0: { michael@0: return handleComputeMonthStart(extendedYear, month+1, TRUE) - michael@0: handleComputeMonthStart(extendedYear, month, TRUE); michael@0: } michael@0: michael@0: int32_t Calendar::handleGetYearLength(int32_t eyear) const { michael@0: return handleComputeMonthStart(eyear+1, 0, FALSE) - michael@0: handleComputeMonthStart(eyear, 0, FALSE); michael@0: } michael@0: michael@0: int32_t michael@0: Calendar::getActualMaximum(UCalendarDateFields field, UErrorCode& status) const michael@0: { michael@0: int32_t result; michael@0: switch (field) { michael@0: case UCAL_DATE: michael@0: { michael@0: if(U_FAILURE(status)) return 0; michael@0: Calendar *cal = clone(); michael@0: if(!cal) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } michael@0: cal->setLenient(TRUE); michael@0: cal->prepareGetActual(field,FALSE,status); michael@0: result = handleGetMonthLength(cal->get(UCAL_EXTENDED_YEAR, status), cal->get(UCAL_MONTH, status)); michael@0: delete cal; michael@0: } michael@0: break; michael@0: michael@0: case UCAL_DAY_OF_YEAR: michael@0: { michael@0: if(U_FAILURE(status)) return 0; michael@0: Calendar *cal = clone(); michael@0: if(!cal) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } michael@0: cal->setLenient(TRUE); michael@0: cal->prepareGetActual(field,FALSE,status); michael@0: result = handleGetYearLength(cal->get(UCAL_EXTENDED_YEAR, status)); michael@0: delete cal; michael@0: } michael@0: break; michael@0: michael@0: case UCAL_DAY_OF_WEEK: michael@0: case UCAL_AM_PM: michael@0: case UCAL_HOUR: michael@0: case UCAL_HOUR_OF_DAY: michael@0: case UCAL_MINUTE: michael@0: case UCAL_SECOND: michael@0: case UCAL_MILLISECOND: michael@0: case UCAL_ZONE_OFFSET: michael@0: case UCAL_DST_OFFSET: michael@0: case UCAL_DOW_LOCAL: michael@0: case UCAL_JULIAN_DAY: michael@0: case UCAL_MILLISECONDS_IN_DAY: michael@0: // These fields all have fixed minima/maxima michael@0: result = getMaximum(field); michael@0: break; michael@0: michael@0: default: michael@0: // For all other fields, do it the hard way.... michael@0: result = getActualHelper(field, getLeastMaximum(field), getMaximum(field),status); michael@0: break; michael@0: } michael@0: return result; michael@0: } michael@0: michael@0: michael@0: /** michael@0: * Prepare this calendar for computing the actual minimum or maximum. michael@0: * This method modifies this calendar's fields; it is called on a michael@0: * temporary calendar. michael@0: * michael@0: *

Rationale: The semantics of getActualXxx() is to return the michael@0: * maximum or minimum value that the given field can take, taking into michael@0: * account other relevant fields. In general these other fields are michael@0: * larger fields. For example, when computing the actual maximum michael@0: * DATE, the current value of DATE itself is ignored, michael@0: * as is the value of any field smaller. michael@0: * michael@0: *

The time fields all have fixed minima and maxima, so we don't michael@0: * need to worry about them. This also lets us set the michael@0: * MILLISECONDS_IN_DAY to zero to erase any effects the time fields michael@0: * might have when computing date fields. michael@0: * michael@0: *

DAY_OF_WEEK is adjusted specially for the WEEK_OF_MONTH and michael@0: * WEEK_OF_YEAR fields to ensure that they are computed correctly. michael@0: * @internal michael@0: */ michael@0: void Calendar::prepareGetActual(UCalendarDateFields field, UBool isMinimum, UErrorCode &status) michael@0: { michael@0: set(UCAL_MILLISECONDS_IN_DAY, 0); michael@0: michael@0: switch (field) { michael@0: case UCAL_YEAR: michael@0: case UCAL_EXTENDED_YEAR: michael@0: set(UCAL_DAY_OF_YEAR, getGreatestMinimum(UCAL_DAY_OF_YEAR)); michael@0: break; michael@0: michael@0: case UCAL_YEAR_WOY: michael@0: set(UCAL_WEEK_OF_YEAR, getGreatestMinimum(UCAL_WEEK_OF_YEAR)); michael@0: michael@0: case UCAL_MONTH: michael@0: set(UCAL_DATE, getGreatestMinimum(UCAL_DATE)); michael@0: break; michael@0: michael@0: case UCAL_DAY_OF_WEEK_IN_MONTH: michael@0: // For dowim, the maximum occurs for the DOW of the first of the michael@0: // month. michael@0: set(UCAL_DATE, 1); michael@0: set(UCAL_DAY_OF_WEEK, get(UCAL_DAY_OF_WEEK, status)); // Make this user set michael@0: break; michael@0: michael@0: case UCAL_WEEK_OF_MONTH: michael@0: case UCAL_WEEK_OF_YEAR: michael@0: // If we're counting weeks, set the day of the week to either the michael@0: // first or last localized DOW. We know the last week of a month michael@0: // or year will contain the first day of the week, and that the michael@0: // first week will contain the last DOW. michael@0: { michael@0: int32_t dow = fFirstDayOfWeek; michael@0: if (isMinimum) { michael@0: dow = (dow + 6) % 7; // set to last DOW michael@0: if (dow < UCAL_SUNDAY) { michael@0: dow += 7; michael@0: } michael@0: } michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "prepareGetActualHelper(WOM/WOY) - dow=%d\n", dow); michael@0: #endif michael@0: set(UCAL_DAY_OF_WEEK, dow); michael@0: } michael@0: break; michael@0: default: michael@0: break; michael@0: } michael@0: michael@0: // Do this last to give it the newest time stamp michael@0: set(field, getGreatestMinimum(field)); michael@0: } michael@0: michael@0: int32_t Calendar::getActualHelper(UCalendarDateFields field, int32_t startValue, int32_t endValue, UErrorCode &status) const michael@0: { michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "getActualHelper(%d,%d .. %d, %s)\n", field, startValue, endValue, u_errorName(status)); michael@0: #endif michael@0: if (startValue == endValue) { michael@0: // if we know that the maximum value is always the same, just return it michael@0: return startValue; michael@0: } michael@0: michael@0: int32_t delta = (endValue > startValue) ? 1 : -1; michael@0: michael@0: // clone the calendar so we don't mess with the real one, and set it to michael@0: // accept anything for the field values michael@0: if(U_FAILURE(status)) return startValue; michael@0: Calendar *work = clone(); michael@0: if(!work) { status = U_MEMORY_ALLOCATION_ERROR; return startValue; } michael@0: michael@0: // need to resolve time here, otherwise, fields set for actual limit michael@0: // may cause conflict with fields previously set (but not yet resolved). michael@0: work->complete(status); michael@0: michael@0: work->setLenient(TRUE); michael@0: work->prepareGetActual(field, delta < 0, status); michael@0: michael@0: // now try each value from the start to the end one by one until michael@0: // we get a value that normalizes to another value. The last value that michael@0: // normalizes to itself is the actual maximum for the current date michael@0: work->set(field, startValue); michael@0: michael@0: // prepareGetActual sets the first day of week in the same week with michael@0: // the first day of a month. Unlike WEEK_OF_YEAR, week number for the michael@0: // week which contains days from both previous and current month is michael@0: // not unique. For example, last several days in the previous month michael@0: // is week 5, and the rest of week is week 1. michael@0: int32_t result = startValue; michael@0: if ((work->get(field, status) != startValue michael@0: && field != UCAL_WEEK_OF_MONTH && delta > 0 ) || U_FAILURE(status)) { michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "getActualHelper(fld %d) - got %d (not %d) - %s\n", field, work->get(field,status), startValue, u_errorName(status)); michael@0: #endif michael@0: } else { michael@0: do { michael@0: startValue += delta; michael@0: work->add(field, delta, status); michael@0: if (work->get(field, status) != startValue || U_FAILURE(status)) { michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "getActualHelper(fld %d) - got %d (not %d), BREAK - %s\n", field, work->get(field,status), startValue, u_errorName(status)); michael@0: #endif michael@0: break; michael@0: } michael@0: result = startValue; michael@0: } while (startValue != endValue); michael@0: } michael@0: delete work; michael@0: #if defined (U_DEBUG_CAL) michael@0: fprintf(stderr, "getActualHelper(%d) = %d\n", field, result); michael@0: #endif michael@0: return result; michael@0: } michael@0: michael@0: michael@0: michael@0: michael@0: // ------------------------------------- michael@0: michael@0: void michael@0: Calendar::setWeekData(const Locale& desiredLocale, const char *type, UErrorCode& status) michael@0: { michael@0: michael@0: if (U_FAILURE(status)) return; michael@0: michael@0: fFirstDayOfWeek = UCAL_SUNDAY; michael@0: fMinimalDaysInFirstWeek = 1; michael@0: fWeekendOnset = UCAL_SATURDAY; michael@0: fWeekendOnsetMillis = 0; michael@0: fWeekendCease = UCAL_SUNDAY; michael@0: fWeekendCeaseMillis = 86400000; // 24*60*60*1000 michael@0: michael@0: // Since week and weekend data is territory based instead of language based, michael@0: // we may need to tweak the locale that we are using to try to get the appropriate michael@0: // values, using the following logic: michael@0: // 1). If the locale has a language but no territory, use the territory as defined by michael@0: // the likely subtags. michael@0: // 2). If the locale has a script designation then we ignore it, michael@0: // then remove it ( i.e. "en_Latn_US" becomes "en_US" ) michael@0: michael@0: char minLocaleID[ULOC_FULLNAME_CAPACITY] = { 0 }; michael@0: UErrorCode myStatus = U_ZERO_ERROR; michael@0: michael@0: uloc_minimizeSubtags(desiredLocale.getName(),minLocaleID,ULOC_FULLNAME_CAPACITY,&myStatus); michael@0: Locale min = Locale::createFromName(minLocaleID); michael@0: Locale useLocale; michael@0: if ( uprv_strlen(desiredLocale.getCountry()) == 0 || michael@0: (uprv_strlen(desiredLocale.getScript()) > 0 && uprv_strlen(min.getScript()) == 0) ) { michael@0: char maxLocaleID[ULOC_FULLNAME_CAPACITY] = { 0 }; michael@0: myStatus = U_ZERO_ERROR; michael@0: uloc_addLikelySubtags(desiredLocale.getName(),maxLocaleID,ULOC_FULLNAME_CAPACITY,&myStatus); michael@0: Locale max = Locale::createFromName(maxLocaleID); michael@0: useLocale = Locale(max.getLanguage(),max.getCountry()); michael@0: } else { michael@0: useLocale = Locale(desiredLocale); michael@0: } michael@0: michael@0: /* The code here is somewhat of a hack, since week data and weekend data aren't really tied to michael@0: a specific calendar, they aren't truly locale data. But this is the only place where valid and michael@0: actual locale can be set, so we take a shot at it here by loading a representative resource michael@0: from the calendar data. The code used to use the dateTimeElements resource to get first day michael@0: of week data, but this was moved to supplemental data under ticket 7755. (JCE) */ michael@0: michael@0: CalendarData calData(useLocale,type,status); michael@0: UResourceBundle *monthNames = calData.getByKey(gMonthNames,status); michael@0: if (U_SUCCESS(status)) { michael@0: U_LOCALE_BASED(locBased,*this); michael@0: locBased.setLocaleIDs(ures_getLocaleByType(monthNames, ULOC_VALID_LOCALE, &status), michael@0: ures_getLocaleByType(monthNames, ULOC_ACTUAL_LOCALE, &status)); michael@0: } else { michael@0: status = U_USING_FALLBACK_WARNING; michael@0: return; michael@0: } michael@0: michael@0: michael@0: // Read week data values from supplementalData week data michael@0: UResourceBundle *rb = ures_openDirect(NULL, "supplementalData", &status); michael@0: ures_getByKey(rb, "weekData", rb, &status); michael@0: UResourceBundle *weekData = ures_getByKey(rb, useLocale.getCountry(), NULL, &status); michael@0: if (status == U_MISSING_RESOURCE_ERROR && rb != NULL) { michael@0: status = U_ZERO_ERROR; michael@0: weekData = ures_getByKey(rb, "001", NULL, &status); michael@0: } michael@0: michael@0: if (U_FAILURE(status)) { michael@0: #if defined (U_DEBUG_CALDATA) michael@0: fprintf(stderr, " Failure loading weekData from supplemental = %s\n", u_errorName(status)); michael@0: #endif michael@0: status = U_USING_FALLBACK_WARNING; michael@0: } else { michael@0: int32_t arrLen; michael@0: const int32_t *weekDataArr = ures_getIntVector(weekData,&arrLen,&status); michael@0: if( U_SUCCESS(status) && arrLen == 6 michael@0: && 1 <= weekDataArr[0] && weekDataArr[0] <= 7 michael@0: && 1 <= weekDataArr[1] && weekDataArr[1] <= 7 michael@0: && 1 <= weekDataArr[2] && weekDataArr[2] <= 7 michael@0: && 1 <= weekDataArr[4] && weekDataArr[4] <= 7) { michael@0: fFirstDayOfWeek = (UCalendarDaysOfWeek)weekDataArr[0]; michael@0: fMinimalDaysInFirstWeek = (uint8_t)weekDataArr[1]; michael@0: fWeekendOnset = (UCalendarDaysOfWeek)weekDataArr[2]; michael@0: fWeekendOnsetMillis = weekDataArr[3]; michael@0: fWeekendCease = (UCalendarDaysOfWeek)weekDataArr[4]; michael@0: fWeekendCeaseMillis = weekDataArr[5]; michael@0: } else { michael@0: status = U_INVALID_FORMAT_ERROR; michael@0: } michael@0: } michael@0: ures_close(weekData); michael@0: ures_close(rb); michael@0: } michael@0: michael@0: /** michael@0: * Recompute the time and update the status fields isTimeSet michael@0: * and areFieldsSet. Callers should check isTimeSet and only michael@0: * call this method if isTimeSet is false. michael@0: */ michael@0: void michael@0: Calendar::updateTime(UErrorCode& status) michael@0: { michael@0: computeTime(status); michael@0: if(U_FAILURE(status)) michael@0: return; michael@0: michael@0: // If we are lenient, we need to recompute the fields to normalize michael@0: // the values. Also, if we haven't set all the fields yet (i.e., michael@0: // in a newly-created object), we need to fill in the fields. [LIU] michael@0: if (isLenient() || ! fAreAllFieldsSet) michael@0: fAreFieldsSet = FALSE; michael@0: michael@0: fIsTimeSet = TRUE; michael@0: fAreFieldsVirtuallySet = FALSE; michael@0: } michael@0: michael@0: Locale michael@0: Calendar::getLocale(ULocDataLocaleType type, UErrorCode& status) const { michael@0: U_LOCALE_BASED(locBased, *this); michael@0: return locBased.getLocale(type, status); michael@0: } michael@0: michael@0: const char * michael@0: Calendar::getLocaleID(ULocDataLocaleType type, UErrorCode& status) const { michael@0: U_LOCALE_BASED(locBased, *this); michael@0: return locBased.getLocaleID(type, status); michael@0: } michael@0: michael@0: void michael@0: Calendar::recalculateStamp() { michael@0: int32_t index; michael@0: int32_t currentValue; michael@0: int32_t j, i; michael@0: michael@0: fNextStamp = 1; michael@0: michael@0: for (j = 0; j < UCAL_FIELD_COUNT; j++) { michael@0: currentValue = STAMP_MAX; michael@0: index = -1; michael@0: for (i = 0; i < UCAL_FIELD_COUNT; i++) { michael@0: if (fStamp[i] > fNextStamp && fStamp[i] < currentValue) { michael@0: currentValue = fStamp[i]; michael@0: index = i; michael@0: } michael@0: } michael@0: michael@0: if (index >= 0) { michael@0: fStamp[index] = ++fNextStamp; michael@0: } else { michael@0: break; michael@0: } michael@0: } michael@0: fNextStamp++; michael@0: } michael@0: michael@0: // Deprecated function. This doesn't need to be inline. michael@0: void michael@0: Calendar::internalSet(EDateFields field, int32_t value) michael@0: { michael@0: internalSet((UCalendarDateFields) field, value); michael@0: } michael@0: michael@0: BasicTimeZone* michael@0: Calendar::getBasicTimeZone(void) const { michael@0: if (dynamic_cast(fZone) != NULL michael@0: || dynamic_cast(fZone) != NULL michael@0: || dynamic_cast(fZone) != NULL michael@0: || dynamic_cast(fZone) != NULL) { michael@0: return (BasicTimeZone*)fZone; michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: U_NAMESPACE_END michael@0: michael@0: #endif /* #if !UCONFIG_NO_FORMATTING */ michael@0: michael@0: michael@0: //eof michael@0: