2 *******************************************************************************
3 * Copyright (C) 1997-2004, International Business Machines Corporation and *
4 * others. All Rights Reserved. *
5 *******************************************************************************
9 * Modification History:
11 * Date Name Description
12 * 02/03/97 clhuang Creation.
13 * 04/22/97 aliu Cleaned up, fixed memory leak, made
14 * setWeekCountData() more robust.
15 * Moved platform code to TPlatformUtilities.
16 * 05/01/97 aliu Made equals(), before(), after() arguments const.
17 * 05/20/97 aliu Changed logic of when to compute fields and time
19 * 08/12/97 aliu Added equivalentTo. Misc other fixes.
20 * 07/28/98 stephen Sync up with JDK 1.2
21 * 09/02/98 stephen Sync with JDK 1.2 8/31 build (getActualMin/Max)
22 * 03/17/99 stephen Changed adoptTimeZone() - now fAreFieldsSet is
23 * set to FALSE to force update of time.
24 *******************************************************************************
27 #include "unicode/utypes.h"
29 #if !UCONFIG_NO_FORMATTING
31 #include "unicode/gregocal.h"
38 #include "unicode/calendar.h"
46 #if !UCONFIG_NO_SERVICE
47 static ICULocaleService
* gService
= NULL
;
50 // INTERNAL - for cleanup
53 static UBool
calendar_cleanup(void) {
54 #if !UCONFIG_NO_SERVICE
64 // ------------------------------------------
68 //-------------------------------------------
69 //#define U_DEBUG_CALSVC 1
72 #if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL)
77 * convert a UCalendarDateFields into a string - for debugging
79 * @return static string to the field name
82 static const char* fldName(UCalendarDateFields f
) {
84 #define FIELD_NAME_STR(x) case x: return (#x+5)
85 FIELD_NAME_STR( UCAL_ERA
);
86 FIELD_NAME_STR( UCAL_YEAR
);
87 FIELD_NAME_STR( UCAL_MONTH
);
88 FIELD_NAME_STR( UCAL_WEEK_OF_YEAR
);
89 FIELD_NAME_STR( UCAL_WEEK_OF_MONTH
);
90 FIELD_NAME_STR( UCAL_DATE
);
91 FIELD_NAME_STR( UCAL_DAY_OF_YEAR
);
92 FIELD_NAME_STR( UCAL_DAY_OF_WEEK
);
93 FIELD_NAME_STR( UCAL_DAY_OF_WEEK_IN_MONTH
);
94 FIELD_NAME_STR( UCAL_AM_PM
);
95 FIELD_NAME_STR( UCAL_HOUR
);
96 FIELD_NAME_STR( UCAL_HOUR_OF_DAY
);
97 FIELD_NAME_STR( UCAL_MINUTE
);
98 FIELD_NAME_STR( UCAL_SECOND
);
99 FIELD_NAME_STR( UCAL_MILLISECOND
);
100 FIELD_NAME_STR( UCAL_ZONE_OFFSET
);
101 FIELD_NAME_STR( UCAL_DST_OFFSET
);
102 FIELD_NAME_STR( UCAL_YEAR_WOY
);
103 FIELD_NAME_STR( UCAL_DOW_LOCAL
);
104 FIELD_NAME_STR( UCAL_EXTENDED_YEAR
);
105 FIELD_NAME_STR( UCAL_JULIAN_DAY
);
106 FIELD_NAME_STR( UCAL_MILLISECONDS_IN_DAY
);
107 #undef FIELD_NAME_STR
115 static const char * const gBasicCalendars
[] = { "@calendar=gregorian", "@calendar=japanese",
116 "@calendar=buddhist", "@calendar=islamic-civil",
117 "@calendar=islamic", "@calendar=hebrew", "@calendar=chinese",
122 static UBool
isStandardSupportedID( const char *id
, UErrorCode
& status
) {
123 if(U_FAILURE(status
)) {
126 for(int32_t i
=0;gBasicCalendars
[i
] != NULL
;i
++) {
127 if(uprv_strcmp(gBasicCalendars
[i
],id
) == 0) {
134 static Calendar
*createStandardCalendar(char *calType
, const Locale
&canLoc
, UErrorCode
& status
) {
135 #ifdef U_DEBUG_CALSVC
136 fprintf(stderr
, "BasicCalendarFactory %p: creating type for %s\n",
137 this, (const char*)curLoc
.getName());
141 if(!calType
|| !*calType
|| !uprv_strcmp(calType
,"@calendar=gregorian")) { // Gregorian (default)
142 return new GregorianCalendar(canLoc
, status
);
143 } else if(!uprv_strcmp(calType
, "@calendar=japanese")) {
144 return new JapaneseCalendar(canLoc
, status
);
145 } else if(!uprv_strcmp(calType
, "@calendar=buddhist")) {
146 return new BuddhistCalendar(canLoc
, status
);
147 } else if(!uprv_strcmp(calType
, "@calendar=islamic-civil")) {
148 return new IslamicCalendar(canLoc
, status
, IslamicCalendar::CIVIL
);
149 } else if(!uprv_strcmp(calType
, "@calendar=islamic")) {
150 return new IslamicCalendar(canLoc
, status
, IslamicCalendar::ASTRONOMICAL
);
151 } else if(!uprv_strcmp(calType
, "@calendar=hebrew")) {
152 return new HebrewCalendar(canLoc
, status
);
153 //} else if(!uprv_strcmp(calType, "@calendar=chinese")) {
154 //return new ChineseCalendar(canLoc, status);
156 status
= U_UNSUPPORTED_ERROR
;
161 #if !UCONFIG_NO_SERVICE
163 // -------------------------------------
166 * a Calendar Factory which creates the "basic" calendar types, that is, those
169 class BasicCalendarFactory
: public LocaleKeyFactory
{
172 * @param calendarType static const string (caller owns storage - will be aliased) to calendar type
174 BasicCalendarFactory()
175 : LocaleKeyFactory(LocaleKeyFactory::INVISIBLE
) { }
177 virtual ~BasicCalendarFactory() {}
180 virtual UBool
isSupportedID( const UnicodeString
& id
, UErrorCode
& status
) const {
181 if(U_FAILURE(status
)) {
184 for(int32_t i
=0;gBasicCalendars
[i
] != NULL
;i
++) {
185 UnicodeString
ourId(gBasicCalendars
[i
],"");
193 virtual void updateVisibleIDs(Hashtable
& result
, UErrorCode
& status
) const
195 if (U_SUCCESS(status
)) {
196 for(int32_t i
=0;gBasicCalendars
[i
] != NULL
;i
++) {
197 UnicodeString
id(gBasicCalendars
[i
],"");
198 result
.put(id
, (void*)this, status
);
203 virtual UObject
* create(const ICUServiceKey
& key
, const ICUService
* /*service*/, UErrorCode
& status
) const {
204 #ifdef U_DEBUG_CALSVC
205 if(key
.getDynamicClassID() != LocaleKey::getStaticClassID()) {
206 fprintf(stderr
, "::create - not a LocaleKey!\n");
209 const LocaleKey
& lkey
= (LocaleKey
&)key
;
210 Locale curLoc
; // current locale
211 Locale canLoc
; // Canonical locale
213 lkey
.currentLocale(curLoc
);
214 lkey
.canonicalLocale(canLoc
);
220 // Extract a char* out of it..
221 int32_t len
= str
.length();
222 int32_t actLen
= sizeof(tmp
)-1;
226 str
.extract(0,len
,tmp
);
229 #ifdef U_DEBUG_CALSVC
230 fprintf(stderr
, "BasicCalendarFactory::create() - cur %s, can %s\n", (const char*)curLoc
.getName(), (const char*)canLoc
.getName());
233 if(!isStandardSupportedID(tmp
,status
)) { // Do we handle this type?
234 #ifdef U_DEBUG_CALSVC
236 fprintf(stderr
, "BasicCalendarFactory - not handling %s.[%s]\n", (const char*) curLoc
.getName(), tmp
);
241 return createStandardCalendar(tmp
, canLoc
, status
);
247 * A factory which looks up the DefaultCalendar resource to determine which class of calendar to use
250 class DefaultCalendarFactory
: public ICUResourceBundleFactory
{
252 DefaultCalendarFactory(): ICUResourceBundleFactory() { }
254 virtual UObject
* create(const ICUServiceKey
& key
, const ICUService
* /*service*/, UErrorCode
& status
) const {
256 LocaleKey
&lkey
= (LocaleKey
&)key
;
258 lkey
.currentLocale(loc
);
260 UnicodeString myString
;
262 // attempt keyword lookup
265 if(!loc
.getKeywordValue("calendar", keyword
, sizeof(keyword
)-1, status
)) {
266 // fetch default calendar id
267 char funcEquiv
[ULOC_FULLNAME_CAPACITY
];
268 ures_getFunctionalEquivalent(funcEquiv
, sizeof(funcEquiv
)-1,
269 NULL
, "calendar", "calendar",
271 NULL
, FALSE
, &status
);
272 uloc_getKeywordValue(funcEquiv
, "calendar", keyword
,
273 sizeof(keyword
)-1, &status
);
274 #ifdef U_DEBUG_CALSVC
275 fprintf(stderr
, " getFunctionalEquivalent calendar=%s [%s]\n", keyword
, u_errorName(status
));
278 #ifdef U_DEBUG_CALSVC
279 else { fprintf(stderr
, " explicit calendar=%s\n", keyword
); }
283 if(U_FAILURE(status
)) {
286 UnicodeString
*ret
= new UnicodeString();
287 ret
->append((UChar
)0x40); // '@' is a variant character
288 ret
->append(UNICODE_STRING("calendar=", 9));
289 (*ret
) += UnicodeString(keyword
,-1,US_INV
);
295 // -------------------------------------
296 class CalendarService
: public ICULocaleService
{
299 : ICULocaleService(UNICODE_STRING_SIMPLE("Calendar"))
301 UErrorCode status
= U_ZERO_ERROR
;
302 registerFactory(new DefaultCalendarFactory(), status
);
305 virtual UObject
* cloneInstance(UObject
* instance
) const {
306 if(instance
->getDynamicClassID() == UnicodeString::getStaticClassID()) {
307 return ((UnicodeString
*)instance
)->clone();
309 #ifdef U_DEBUG_CALSVC_F
310 UErrorCode status2
= U_ZERO_ERROR
;
311 fprintf(stderr
, "Cloning a %s calendar with tz=%ld\n", ((Calendar
*)instance
)->getType(), ((Calendar
*)instance
)->get(UCAL_ZONE_OFFSET
, status2
));
313 return ((Calendar
*)instance
)->clone();
317 virtual UObject
* handleDefault(const ICUServiceKey
& key
, UnicodeString
* /*actualID*/, UErrorCode
& status
) const {
318 LocaleKey
& lkey
= (LocaleKey
&)key
;
319 //int32_t kind = lkey.kind();
322 lkey
.canonicalLocale(loc
);
324 #ifdef U_DEBUG_CALSVC
326 lkey
.currentLocale(loc2
);
327 fprintf(stderr
, "CalSvc:handleDefault for currentLoc %s, canloc %s\n", (const char*)loc
.getName(), (const char*)loc2
.getName());
329 Calendar
*nc
= new GregorianCalendar(loc
, status
);
331 #ifdef U_DEBUG_CALSVC
332 UErrorCode status2
= U_ZERO_ERROR
;
333 fprintf(stderr
, "New default calendar has tz=%d\n", ((Calendar
*)nc
)->get(UCAL_ZONE_OFFSET
, status2
));
338 virtual UBool
isDefault() const {
339 return countFactories() == 1;
343 // -------------------------------------
346 isCalendarServiceUsed() {
348 return (UBool
)(gService
!= NULL
);
351 // -------------------------------------
353 static ICULocaleService
*
354 getCalendarService(UErrorCode
&status
)
359 needInit
= (UBool
)(gService
== NULL
);
362 #ifdef U_DEBUG_CALSVC
363 fprintf(stderr
, "Spinning up Calendar Service\n");
365 ICULocaleService
* newservice
= new CalendarService();
366 #ifdef U_DEBUG_CALSVC
367 fprintf(stderr
, "Registering classes..\n");
370 // Register all basic instances.
371 newservice
->registerFactory(new BasicCalendarFactory(),status
);
373 #ifdef U_DEBUG_CALSVC
374 fprintf(stderr
, "Done..\n");
377 if(U_FAILURE(status
)) {
378 #ifdef U_DEBUG_CALSVC
379 fprintf(stderr
, "err (%s) registering classes, deleting service.....\n", u_errorName(status
));
387 if (gService
== NULL
) {
388 gService
= newservice
;
395 // we won the contention - we can register the cleanup.
396 ucln_i18n_registerCleanup(UCLN_I18N_CALENDAR
, calendar_cleanup
);
402 URegistryKey
Calendar::registerFactory(ICUServiceFactory
* toAdopt
, UErrorCode
& status
)
404 return getCalendarService(status
)->registerFactory(toAdopt
, status
);
407 UBool
Calendar::unregister(URegistryKey key
, UErrorCode
& status
) {
408 return getCalendarService(status
)->unregister(key
, status
);
410 #endif /* UCONFIG_NO_SERVICE */
412 // -------------------------------------
414 static const int32_t kCalendarLimits
[UCAL_FIELD_COUNT
][4] = {
415 // Minimum Greatest min Least max Greatest max
416 {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // ERA
417 {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // YEAR
418 {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // MONTH
419 {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // WEEK_OF_YEAR
420 {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // WEEK_OF_MONTH
421 {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_MONTH
422 {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_YEAR
423 { 1, 1, 7, 7 }, // DAY_OF_WEEK
424 {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_WEEK_IN_MONTH
425 { 0, 0, 1, 1 }, // AM_PM
426 { 0, 0, 11, 11 }, // HOUR
427 { 0, 0, 23, 23 }, // HOUR_OF_DAY
428 { 0, 0, 59, 59 }, // MINUTE
429 { 0, 0, 59, 59 }, // SECOND
430 { 0, 0, 999, 999 }, // MILLISECOND
431 {-12*kOneHour
, -12*kOneHour
, 12*kOneHour
, 15*kOneHour
}, // ZONE_OFFSET
432 { 0, 0, 1*kOneHour
, 1*kOneHour
}, // DST_OFFSET
433 {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // YEAR_WOY
434 { 1, 1, 7, 7 }, // DOW_LOCAL
435 {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // EXTENDED_YEAR
436 { -0x7F000000, -0x7F000000, 0x7F000000, 0x7F000000 }, // JULIAN_DAY
437 { 0, 0, 24*kOneHour
-1, 24*kOneHour
-1 } // MILLISECONDS_IN_DAY
440 // Resource bundle tags read by this class
441 const char Calendar::kDateTimeElements
[] = "DateTimeElements";
443 // Data flow in Calendar
444 // ---------------------
446 // The current time is represented in two ways by Calendar: as UTC
447 // milliseconds from the epoch start (1 January 1970 0:00 UTC), and as local
448 // fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the
449 // millis from the fields, and vice versa. The data needed to do this
450 // conversion is encapsulated by a TimeZone object owned by the Calendar.
451 // The data provided by the TimeZone object may also be overridden if the
452 // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
453 // keeps track of what information was most recently set by the caller, and
454 // uses that to compute any other information as needed.
456 // If the user sets the fields using set(), the data flow is as follows.
457 // This is implemented by the Calendar subclass's computeTime() method.
458 // During this process, certain fields may be ignored. The disambiguation
459 // algorithm for resolving which fields to pay attention to is described
462 // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
464 // | Using Calendar-specific algorithm
466 // local standard millis
468 // | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
470 // UTC millis (in time data member)
472 // If the user sets the UTC millis using setTime(), the data flow is as
473 // follows. This is implemented by the Calendar subclass's computeFields()
476 // UTC millis (in time data member)
478 // | Using TimeZone getOffset()
480 // local standard millis
482 // | Using Calendar-specific algorithm
484 // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
486 // In general, a round trip from fields, through local and UTC millis, and
487 // back out to fields is made when necessary. This is implemented by the
488 // complete() method. Resolving a partial set of fields into a UTC millis
489 // value allows all remaining fields to be generated from that value. If
490 // the Calendar is lenient, the fields are also renormalized to standard
491 // ranges when they are regenerated.
493 // -------------------------------------
495 Calendar::Calendar(UErrorCode
& success
)
498 fAreFieldsSet(FALSE
),
499 fAreAllFieldsSet(FALSE
),
500 fAreFieldsVirtuallySet(FALSE
),
501 fNextStamp((int32_t)kMinimumUserStamp
),
507 fZone
= TimeZone::createDefault();
508 setWeekCountData(Locale::getDefault(), NULL
, success
);
511 // -------------------------------------
513 Calendar::Calendar(TimeZone
* zone
, const Locale
& aLocale
, UErrorCode
& success
)
516 fAreFieldsSet(FALSE
),
517 fAreAllFieldsSet(FALSE
),
518 fAreFieldsVirtuallySet(FALSE
),
519 fNextStamp((int32_t)kMinimumUserStamp
),
525 #if defined (U_DEBUG_CAL)
526 fprintf(stderr
, "%s:%d: ILLEGAL ARG because timezone cannot be 0\n",
529 success
= U_ILLEGAL_ARGUMENT_ERROR
;
536 setWeekCountData(aLocale
, NULL
, success
);
539 // -------------------------------------
541 Calendar::Calendar(const TimeZone
& zone
, const Locale
& aLocale
, UErrorCode
& success
)
544 fAreFieldsSet(FALSE
),
545 fAreAllFieldsSet(FALSE
),
546 fAreFieldsVirtuallySet(FALSE
),
547 fNextStamp((int32_t)kMinimumUserStamp
),
553 fZone
= zone
.clone();
554 setWeekCountData(aLocale
, NULL
, success
);
557 // -------------------------------------
559 Calendar::~Calendar()
564 // -------------------------------------
566 Calendar::Calendar(const Calendar
&source
)
573 // -------------------------------------
576 Calendar::operator=(const Calendar
&right
)
578 if (this != &right
) {
579 uprv_arrayCopy(right
.fFields
, fFields
, UCAL_FIELD_COUNT
);
580 uprv_arrayCopy(right
.fIsSet
, fIsSet
, UCAL_FIELD_COUNT
);
581 uprv_arrayCopy(right
.fStamp
, fStamp
, UCAL_FIELD_COUNT
);
583 fIsTimeSet
= right
.fIsTimeSet
;
584 fAreAllFieldsSet
= right
.fAreAllFieldsSet
;
585 fAreFieldsSet
= right
.fAreFieldsSet
;
586 fAreFieldsVirtuallySet
= right
.fAreFieldsVirtuallySet
;
587 fLenient
= right
.fLenient
;
589 fZone
= right
.fZone
->clone();
590 fFirstDayOfWeek
= right
.fFirstDayOfWeek
;
591 fMinimalDaysInFirstWeek
= right
.fMinimalDaysInFirstWeek
;
592 fNextStamp
= right
.fNextStamp
;
598 // -------------------------------------
601 Calendar::createInstance(UErrorCode
& success
)
603 return createInstance(TimeZone::createDefault(), Locale::getDefault(), success
);
606 // -------------------------------------
609 Calendar::createInstance(const TimeZone
& zone
, UErrorCode
& success
)
611 return createInstance(zone
, Locale::getDefault(), success
);
614 // -------------------------------------
617 Calendar::createInstance(const Locale
& aLocale
, UErrorCode
& success
)
619 return createInstance(TimeZone::createDefault(), aLocale
, success
);
622 // ------------------------------------- Adopting
624 // Note: this is the bottleneck that actually calls the service routines.
627 Calendar::createInstance(TimeZone
* zone
, const Locale
& aLocale
, UErrorCode
& success
)
631 #if !UCONFIG_NO_SERVICE
632 if (isCalendarServiceUsed()) {
633 u
= getCalendarService(success
)->get(aLocale
, LocaleKey::KIND_ANY
, &actualLoc
, success
);
638 char calLocaleType
[ULOC_FULLNAME_CAPACITY
] = {"@calendar="};
639 int32_t calLocaleTypeLen
= uprv_strlen(calLocaleType
);
640 int32_t keywordCapacity
= aLocale
.getKeywordValue("calendar", calLocaleType
+calLocaleTypeLen
, sizeof(calLocaleType
)-calLocaleTypeLen
-1, success
);
641 if (keywordCapacity
== 0) {
642 char funcEquiv
[ULOC_FULLNAME_CAPACITY
];
644 // fetch default calendar id
645 ures_getFunctionalEquivalent(funcEquiv
, sizeof(funcEquiv
)-1,
646 NULL
, "calendar", "calendar",
648 NULL
, FALSE
, &success
);
649 keywordCapacity
= uloc_getKeywordValue(funcEquiv
, "calendar", calLocaleType
+calLocaleTypeLen
,
650 sizeof(calLocaleType
)-calLocaleTypeLen
-1, &success
);
651 if (keywordCapacity
== 0 || U_FAILURE(success
)) {
652 // no calendar type. Default to nothing.
653 calLocaleType
[0] = 0;
655 #ifdef U_DEBUG_CALSVC
656 fprintf(stderr
, " getFunctionalEquivalent calendar=%s [%s]\n", keyword
, u_errorName(status
));
659 #ifdef U_DEBUG_CALSVC
660 else { fprintf(stderr
, " explicit calendar=%s\n", keyword
); }
662 u
= createStandardCalendar(calLocaleType
, aLocale
, success
);
666 if(U_FAILURE(success
) || !u
) {
668 if(U_SUCCESS(success
)) { // Propagate some kind of err
669 success
= U_INTERNAL_PROGRAM_ERROR
;
674 #if !UCONFIG_NO_SERVICE
675 if(u
->getDynamicClassID() == UnicodeString::getStaticClassID()) {
676 // It's a unicode string telling us what type of calendar to load ("gregorian", etc)
678 const UnicodeString
& str
= *(UnicodeString
*)u
;
679 // Extract a char* out of it..
680 int32_t len
= str
.length();
681 int32_t actLen
= sizeof(tmp
)-1;
685 str
.extract(0,len
,tmp
);
688 #ifdef U_DEBUG_CALSVC
689 fprintf(stderr
, "Calendar::createInstance(%s), fetched string %s..\n", (const char*)aLocale
.getName(), tmp
);
692 // Create a Locale over this string
693 Locale l
= Locale::createFromName(tmp
);
695 #ifdef U_DEBUG_CALSVC
696 fprintf(stderr
, "looking up [%s].. should be %s\n",l
.getName(), tmp
);
703 // Don't overwrite actualLoc, since the actual loc from this call
704 // may be something like "@calendar=gregorian" -- TODO investigate
706 c
= (Calendar
*)getCalendarService(success
)->get(l
, LocaleKey::KIND_ANY
, &actualLoc2
, success
);
708 if(U_FAILURE(success
) || !c
) {
710 if(U_SUCCESS(success
)) {
711 success
= U_INTERNAL_PROGRAM_ERROR
; // Propagate some err
716 if(c
->getDynamicClassID() == UnicodeString::getStaticClassID()) {
717 // recursed! Second lookup returned a UnicodeString.
718 // Perhaps DefaultCalendar{} was set to another locale.
719 #ifdef U_DEBUG_CALSVC
721 const UnicodeString
& str
= *(UnicodeString
*)c
;
722 // Extract a char* out of it..
723 int32_t len
= str
.length();
724 int32_t actLen
= sizeof(tmp
)-1;
728 str
.extract(0,len
,tmp
);
731 fprintf(stderr
, "err - recursed, 2nd lookup was unistring %s\n", tmp
);
733 success
= U_MISSING_RESOURCE_ERROR
; // requested a calendar type which could NOT be found.
738 #ifdef U_DEBUG_CALSVC
739 fprintf(stderr
, "%p: setting week count data to locale %s, actual locale %s\n", c
, (const char*)aLocale
.getName(), (const char *)actualLoc
.getName());
741 c
->setWeekCountData(aLocale
, c
->getType(), success
); // set the correct locale (this was an indirected calendar)
744 #endif /* UCONFIG_NO_SERVICE */
746 // a calendar was returned - we assume the factory did the right thing.
750 // Now, reset calendar to default state:
751 c
->adoptTimeZone(zone
); // Set the correct time zone
752 c
->setTimeInMillis(getNow(), success
); // let the new calendar have the current time.
757 // -------------------------------------
760 Calendar::createInstance(const TimeZone
& zone
, const Locale
& aLocale
, UErrorCode
& success
)
762 Calendar
* c
= createInstance(aLocale
, success
);
763 if(U_SUCCESS(success
) && c
) {
764 c
->setTimeZone(zone
);
769 // -------------------------------------
772 Calendar::operator==(const Calendar
& that
) const
774 UErrorCode status
= U_ZERO_ERROR
;
775 return isEquivalentTo(that
) &&
776 getTimeInMillis(status
) == that
.getTimeInMillis(status
) &&
781 Calendar::isEquivalentTo(const Calendar
& other
) const
783 return getDynamicClassID() == other
.getDynamicClassID() &&
784 fLenient
== other
.fLenient
&&
785 fFirstDayOfWeek
== other
.fFirstDayOfWeek
&&
786 fMinimalDaysInFirstWeek
== other
.fMinimalDaysInFirstWeek
&&
787 *fZone
== *other
.fZone
;
790 // -------------------------------------
793 Calendar::equals(const Calendar
& when
, UErrorCode
& status
) const
795 return (this == &when
||
796 getTime(status
) == when
.getTime(status
));
799 // -------------------------------------
802 Calendar::before(const Calendar
& when
, UErrorCode
& status
) const
804 return (this != &when
&&
805 getTimeInMillis(status
) < when
.getTimeInMillis(status
));
808 // -------------------------------------
811 Calendar::after(const Calendar
& when
, UErrorCode
& status
) const
813 return (this != &when
&&
814 getTimeInMillis(status
) > when
.getTimeInMillis(status
));
817 // -------------------------------------
820 const Locale
* U_EXPORT2
821 Calendar::getAvailableLocales(int32_t& count
)
823 return Locale::getAvailableLocales(count
);
826 // -------------------------------------
831 return uprv_getUTCtime(); // return as milliseconds
834 // -------------------------------------
837 * Gets this Calendar's current time as a long.
838 * @return the current time as UTC milliseconds from the epoch.
841 Calendar::getTimeInMillis(UErrorCode
& status
) const
843 if(U_FAILURE(status
))
847 ((Calendar
*)this)->updateTime(status
);
849 /* Test for buffer overflows */
850 if(U_FAILURE(status
)) {
856 // -------------------------------------
859 * Sets this Calendar's current time from the given long value.
860 * @param date the new time in UTC milliseconds from the epoch.
863 Calendar::setTimeInMillis( double millis
, UErrorCode
& status
) {
864 if(U_FAILURE(status
))
867 if (millis
> MAX_MILLIS
) {
869 } else if (millis
< MIN_MILLIS
) {
874 fAreFieldsSet
= fAreAllFieldsSet
= FALSE
;
875 fIsTimeSet
= fAreFieldsVirtuallySet
= TRUE
;
878 // -------------------------------------
881 Calendar::get(UCalendarDateFields field
, UErrorCode
& status
) const
883 // field values are only computed when actually requested; for more on when computation
884 // of various things happens, see the "data flow in Calendar" description at the top
886 if (U_SUCCESS(status
)) ((Calendar
*)this)->complete(status
); // Cast away const
887 return U_SUCCESS(status
) ? fFields
[field
] : 0;
890 // -------------------------------------
893 Calendar::set(UCalendarDateFields field
, int32_t value
)
895 if (fAreFieldsVirtuallySet
) {
896 UErrorCode ec
= U_ZERO_ERROR
;
899 fFields
[field
] = value
;
900 fStamp
[field
] = fNextStamp
++;
901 fIsSet
[field
] = TRUE
; // Remove later
902 fIsTimeSet
= fAreFieldsSet
= fAreFieldsVirtuallySet
= FALSE
;
905 // -------------------------------------
908 Calendar::set(int32_t year
, int32_t month
, int32_t date
)
910 set(UCAL_YEAR
, year
);
911 set(UCAL_MONTH
, month
);
912 set(UCAL_DATE
, date
);
915 // -------------------------------------
918 Calendar::set(int32_t year
, int32_t month
, int32_t date
, int32_t hour
, int32_t minute
)
920 set(UCAL_YEAR
, year
);
921 set(UCAL_MONTH
, month
);
922 set(UCAL_DATE
, date
);
923 set(UCAL_HOUR_OF_DAY
, hour
);
924 set(UCAL_MINUTE
, minute
);
927 // -------------------------------------
930 Calendar::set(int32_t year
, int32_t month
, int32_t date
, int32_t hour
, int32_t minute
, int32_t second
)
932 set(UCAL_YEAR
, year
);
933 set(UCAL_MONTH
, month
);
934 set(UCAL_DATE
, date
);
935 set(UCAL_HOUR_OF_DAY
, hour
);
936 set(UCAL_MINUTE
, minute
);
937 set(UCAL_SECOND
, second
);
940 // -------------------------------------
945 for (int32_t i
=0; i
<UCAL_FIELD_COUNT
; ++i
) {
946 fFields
[i
] = 0; // Must do this; other code depends on it
948 fIsSet
[i
] = FALSE
; // Remove later
950 fIsTimeSet
= fAreFieldsSet
= fAreAllFieldsSet
= fAreFieldsVirtuallySet
= FALSE
;
953 // -------------------------------------
956 Calendar::clear(UCalendarDateFields field
)
958 if (fAreFieldsVirtuallySet
) {
959 UErrorCode ec
= U_ZERO_ERROR
;
963 fStamp
[field
] = kUnset
;
964 fIsSet
[field
] = FALSE
; // Remove later
965 fIsTimeSet
= fAreFieldsSet
= fAreAllFieldsSet
= fAreFieldsVirtuallySet
= FALSE
;
968 // -------------------------------------
971 Calendar::isSet(UCalendarDateFields field
) const
973 return fAreFieldsVirtuallySet
|| (fStamp
[field
] != kUnset
);
977 int32_t Calendar::newestStamp(UCalendarDateFields first
, UCalendarDateFields last
, int32_t bestStampSoFar
) const
979 int32_t bestStamp
= bestStampSoFar
;
980 for (int32_t i
=(int32_t)first
; i
<=(int32_t)last
; ++i
) {
981 if (fStamp
[i
] > bestStamp
) {
982 bestStamp
= fStamp
[i
];
989 // -------------------------------------
992 Calendar::complete(UErrorCode
& status
)
996 /* Test for buffer overflows */
997 if(U_FAILURE(status
)) {
1001 if (!fAreFieldsSet
) {
1002 computeFields(status
); // fills in unset fields
1003 /* Test for buffer overflows */
1004 if(U_FAILURE(status
)) {
1007 fAreFieldsSet
= TRUE
;
1008 fAreAllFieldsSet
= TRUE
;
1012 //-------------------------------------------------------------------------
1013 // Protected utility methods for use by subclasses. These are very handy
1014 // for implementing add, roll, and computeFields.
1015 //-------------------------------------------------------------------------
1018 * Adjust the specified field so that it is within
1019 * the allowable range for the date to which this calendar is set.
1020 * For example, in a Gregorian calendar pinning the {@link #DAY_OF_MONTH DAY_OF_MONTH}
1021 * field for a calendar set to April 31 would cause it to be set
1024 * <b>Subclassing:</b>
1026 * This utility method is intended for use by subclasses that need to implement
1027 * their own overrides of {@link #roll roll} and {@link #add add}.
1030 * <code>pinField</code> is implemented in terms of
1031 * {@link #getActualMinimum getActualMinimum}
1032 * and {@link #getActualMaximum getActualMaximum}. If either of those methods uses
1033 * a slow, iterative algorithm for a particular field, it would be
1034 * unwise to attempt to call <code>pinField</code> for that field. If you
1035 * really do need to do so, you should override this method to do
1036 * something more efficient for that field.
1038 * @param field The calendar field whose value should be pinned.
1040 * @see #getActualMinimum
1041 * @see #getActualMaximum
1044 void Calendar::pinField(UCalendarDateFields field
, UErrorCode
& status
) {
1045 int32_t max
= getActualMaximum(field
, status
);
1046 int32_t min
= getActualMinimum(field
, status
);
1048 if (fFields
[field
] > max
) {
1050 } else if (fFields
[field
] < min
) {
1056 void Calendar::computeFields(UErrorCode
&ec
)
1058 if (U_FAILURE(ec
)) {
1061 // Compute local wall millis
1062 double localMillis
= internalGetTime();
1063 int32_t rawOffset
, dstOffset
;
1064 getTimeZone().getOffset(localMillis
, FALSE
, rawOffset
, dstOffset
, ec
);
1065 localMillis
+= rawOffset
;
1067 // Mark fields as set. Do this before calling handleComputeFields().
1068 uint32_t mask
= //fInternalSetMask;
1072 (1 << UCAL_DAY_OF_MONTH
) | // = UCAL_DATE
1073 (1 << UCAL_DAY_OF_YEAR
) |
1074 (1 << UCAL_EXTENDED_YEAR
);
1076 for (int32_t i
=0; i
<UCAL_FIELD_COUNT
; ++i
) {
1077 if ((mask
& 1) == 0) {
1078 fStamp
[i
] = kInternallySet
;
1079 fIsSet
[i
] = TRUE
; // Remove later
1082 fIsSet
[i
] = FALSE
; // Remove later
1087 // We used to check for and correct extreme millis values (near
1088 // Long.MIN_VALUE or Long.MAX_VALUE) here. Such values would cause
1089 // overflows from positive to negative (or vice versa) and had to
1090 // be manually tweaked. We no longer need to do this because we
1091 // have limited the range of supported dates to those that have a
1092 // Julian day that fits into an int. This allows us to implement a
1093 // JULIAN_DAY field and also removes some inelegant code. - Liu
1096 int32_t days
= (int32_t)Math::floorDivide(localMillis
, (double)kOneDay
);
1098 internalSet(UCAL_JULIAN_DAY
,days
+ kEpochStartAsJulianDay
);
1100 #if defined (U_DEBUG_CAL)
1101 //fprintf(stderr, "%s:%d- Hmm! Jules @ %d, as per %.0lf millis\n",
1102 //__FILE__, __LINE__, fFields[UCAL_JULIAN_DAY], localMillis);
1105 // In some cases we will have to call this method again below to
1106 // adjust for DST pushing us into the next Julian day.
1107 computeGregorianAndDOWFields(fFields
[UCAL_JULIAN_DAY
], ec
);
1109 int32_t millisInDay
= (int32_t) (localMillis
- (days
* kOneDay
));
1110 if (millisInDay
< 0) millisInDay
+= (int32_t)kOneDay
;
1112 // Adjust our millisInDay for DST. dstOffset will be zero if DST
1113 // is not in effect at this time of year, or if our zone does not
1115 millisInDay
+= dstOffset
;
1117 // If DST has pushed us into the next day, we must call
1118 // computeGregorianAndDOWFields() again. This happens in DST between
1119 // 12:00 am and 1:00 am every day. The first call to
1120 // computeGregorianAndDOWFields() will give the wrong day, since the
1121 // Standard time is in the previous day.
1122 if (millisInDay
>= (int32_t)kOneDay
) {
1123 millisInDay
-= (int32_t)kOneDay
; // ASSUME dstOffset < 24:00
1125 // We don't worry about overflow of JULIAN_DAY because the
1126 // allowable range of JULIAN_DAY has slop at the ends (that is,
1127 // the max is less that 0x7FFFFFFF and the min is greater than
1129 computeGregorianAndDOWFields(++fFields
[UCAL_JULIAN_DAY
], ec
);
1132 // Call framework method to have subclass compute its fields.
1133 // These must include, at a minimum, MONTH, DAY_OF_MONTH,
1134 // EXTENDED_YEAR, YEAR, DAY_OF_YEAR. This method will call internalSet(),
1135 // which will update stamp[].
1136 handleComputeFields(fFields
[UCAL_JULIAN_DAY
], ec
);
1138 // Compute week-related fields, based on the subclass-computed
1139 // fields computed by handleComputeFields().
1140 computeWeekFields(ec
);
1142 // Compute time-related fields. These are indepent of the date and
1143 // of the subclass algorithm. They depend only on the local zone
1144 // wall milliseconds in day.
1145 fFields
[UCAL_MILLISECONDS_IN_DAY
] = millisInDay
;
1146 fFields
[UCAL_MILLISECOND
] = millisInDay
% 1000;
1147 millisInDay
/= 1000;
1148 fFields
[UCAL_SECOND
] = millisInDay
% 60;
1150 fFields
[UCAL_MINUTE
] = millisInDay
% 60;
1152 fFields
[UCAL_HOUR_OF_DAY
] = millisInDay
;
1153 fFields
[UCAL_AM_PM
] = millisInDay
/ 12; // Assume AM == 0
1154 fFields
[UCAL_HOUR
] = millisInDay
% 12;
1155 fFields
[UCAL_ZONE_OFFSET
] = rawOffset
;
1156 fFields
[UCAL_DST_OFFSET
] = dstOffset
;
1159 uint8_t Calendar::julianDayToDayOfWeek(double julian
)
1161 // If julian is negative, then julian%7 will be negative, so we adjust
1162 // accordingly. We add 1 because Julian day 0 is Monday.
1163 int8_t dayOfWeek
= (int8_t) uprv_fmod(julian
+ 1, 7);
1165 uint8_t result
= (uint8_t)(dayOfWeek
+ ((dayOfWeek
< 0) ? (7+UCAL_SUNDAY
) : UCAL_SUNDAY
));
1170 * Compute the Gregorian calendar year, month, and day of month from
1171 * the given Julian day. These values are not stored in fields, but in
1172 * member variables gregorianXxx. Also compute the DAY_OF_WEEK and
1175 void Calendar::computeGregorianAndDOWFields(int32_t julianDay
, UErrorCode
&ec
)
1177 computeGregorianFields(julianDay
, ec
);
1179 // Compute day of week: JD 0 = Monday
1180 int32_t dow
= julianDayToDayOfWeek(julianDay
);
1181 internalSet(UCAL_DAY_OF_WEEK
,dow
);
1183 // Calculate 1-based localized day of week
1184 int32_t dowLocal
= dow
- getFirstDayOfWeek() + 1;
1188 internalSet(UCAL_DOW_LOCAL
,dowLocal
);
1189 fFields
[UCAL_DOW_LOCAL
] = dowLocal
;
1193 * Compute the Gregorian calendar year, month, and day of month from the
1194 * Julian day. These values are not stored in fields, but in member
1195 * variables gregorianXxx. They are used for time zone computations and by
1196 * subclasses that are Gregorian derivatives. Subclasses may call this
1197 * method to perform a Gregorian calendar millis->fields computation.
1198 * To perform a Gregorian calendar fields->millis computation, call
1199 * computeGregorianMonthStart().
1200 * @see #computeGregorianMonthStart
1202 void Calendar::computeGregorianFields(int32_t julianDay
, UErrorCode
& /* ec */) {
1203 int32_t gregorianDayOfWeekUnused
;
1204 Grego::dayToFields(julianDay
- kEpochStartAsJulianDay
, fGregorianYear
, fGregorianMonth
, fGregorianDayOfMonth
, gregorianDayOfWeekUnused
, fGregorianDayOfYear
);
1208 * Compute the fields WEEK_OF_YEAR, YEAR_WOY, WEEK_OF_MONTH,
1209 * DAY_OF_WEEK_IN_MONTH, and DOW_LOCAL from EXTENDED_YEAR, YEAR,
1210 * DAY_OF_WEEK, and DAY_OF_YEAR. The latter fields are computed by the
1211 * subclass based on the calendar system.
1213 * <p>The YEAR_WOY field is computed simplistically. It is equal to YEAR
1214 * most of the time, but at the year boundary it may be adjusted to YEAR-1
1215 * or YEAR+1 to reflect the overlap of a week into an adjacent year. In
1216 * this case, a simple increment or decrement is performed on YEAR, even
1217 * though this may yield an invalid YEAR value. For instance, if the YEAR
1218 * is part of a calendar system with an N-year cycle field CYCLE, then
1219 * incrementing the YEAR may involve incrementing CYCLE and setting YEAR
1220 * back to 0 or 1. This is not handled by this code, and in fact cannot be
1221 * simply handled without having subclasses define an entire parallel set of
1222 * fields for fields larger than or equal to a year. This additional
1223 * complexity is not warranted, since the intention of the YEAR_WOY field is
1224 * to support ISO 8601 notation, so it will typically be used with a
1225 * proleptic Gregorian calendar, which has no field larger than a year.
1227 void Calendar::computeWeekFields(UErrorCode
&ec
) {
1231 int32_t eyear
= fFields
[UCAL_EXTENDED_YEAR
];
1232 int32_t year
= fFields
[UCAL_YEAR
];
1233 int32_t dayOfWeek
= fFields
[UCAL_DAY_OF_WEEK
];
1234 int32_t dayOfYear
= fFields
[UCAL_DAY_OF_YEAR
];
1236 // WEEK_OF_YEAR start
1237 // Compute the week of the year. For the Gregorian calendar, valid week
1238 // numbers run from 1 to 52 or 53, depending on the year, the first day
1239 // of the week, and the minimal days in the first week. For other
1240 // calendars, the valid range may be different -- it depends on the year
1241 // length. Days at the start of the year may fall into the last week of
1242 // the previous year; days at the end of the year may fall into the
1243 // first week of the next year. ASSUME that the year length is less than
1245 int32_t yearOfWeekOfYear
= year
;
1246 int32_t relDow
= (dayOfWeek
+ 7 - getFirstDayOfWeek()) % 7; // 0..6
1247 int32_t relDowJan1
= (dayOfWeek
- dayOfYear
+ 7001 - getFirstDayOfWeek()) % 7; // 0..6
1248 int32_t woy
= (dayOfYear
- 1 + relDowJan1
) / 7; // 0..53
1249 if ((7 - relDowJan1
) >= getMinimalDaysInFirstWeek()) {
1253 // Adjust for weeks at the year end that overlap into the previous or
1254 // next calendar year.
1256 // We are the last week of the previous year.
1257 // Check to see if we are in the last week; if so, we need
1258 // to handle the case in which we are the first week of the
1261 int32_t prevDoy
= dayOfYear
+ handleGetYearLength(eyear
- 1);
1262 woy
= weekNumber(prevDoy
, dayOfWeek
);
1265 int32_t lastDoy
= handleGetYearLength(eyear
);
1266 // Fast check: For it to be week 1 of the next year, the DOY
1267 // must be on or after L-5, where L is yearLength(), then it
1268 // cannot possibly be week 1 of the next year:
1270 // doy: 359 360 361 362 363 364 365 001
1271 // dow: 1 2 3 4 5 6 7
1272 if (dayOfYear
>= (lastDoy
- 5)) {
1273 int32_t lastRelDow
= (relDow
+ lastDoy
- dayOfYear
) % 7;
1274 if (lastRelDow
< 0) {
1277 if (((6 - lastRelDow
) >= getMinimalDaysInFirstWeek()) &&
1278 ((dayOfYear
+ 7 - relDow
) > lastDoy
)) {
1284 fFields
[UCAL_WEEK_OF_YEAR
] = woy
;
1285 fFields
[UCAL_YEAR_WOY
] = yearOfWeekOfYear
;
1288 int32_t dayOfMonth
= fFields
[UCAL_DAY_OF_MONTH
];
1289 fFields
[UCAL_WEEK_OF_MONTH
] = weekNumber(dayOfMonth
, dayOfWeek
);
1290 fFields
[UCAL_DAY_OF_WEEK_IN_MONTH
] = (dayOfMonth
-1) / 7 + 1;
1291 #if defined (U_DEBUG_CAL)
1292 if(fFields
[UCAL_DAY_OF_WEEK_IN_MONTH
]==0) fprintf(stderr
, "%s:%d: DOWIM %d on %g\n",
1293 __FILE__
, __LINE__
,fFields
[UCAL_DAY_OF_WEEK_IN_MONTH
], fTime
);
1298 int32_t Calendar::weekNumber(int32_t desiredDay
, int32_t dayOfPeriod
, int32_t dayOfWeek
)
1300 // Determine the day of the week of the first day of the period
1301 // in question (either a year or a month). Zero represents the
1302 // first day of the week on this calendar.
1303 int32_t periodStartDayOfWeek
= (dayOfWeek
- getFirstDayOfWeek() - dayOfPeriod
+ 1) % 7;
1304 if (periodStartDayOfWeek
< 0) periodStartDayOfWeek
+= 7;
1306 // Compute the week number. Initially, ignore the first week, which
1307 // may be fractional (or may not be). We add periodStartDayOfWeek in
1308 // order to fill out the first week, if it is fractional.
1309 int32_t weekNo
= (desiredDay
+ periodStartDayOfWeek
- 1)/7;
1311 // If the first week is long enough, then count it. If
1312 // the minimal days in the first week is one, or if the period start
1313 // is zero, we always increment weekNo.
1314 if ((7 - periodStartDayOfWeek
) >= getMinimalDaysInFirstWeek()) ++weekNo
;
1319 void Calendar::handleComputeFields(int32_t /* julianDay */, UErrorCode
&/* status */)
1321 internalSet(UCAL_MONTH
, getGregorianMonth());
1322 internalSet(UCAL_DAY_OF_MONTH
, getGregorianDayOfMonth());
1323 internalSet(UCAL_DAY_OF_YEAR
, getGregorianDayOfYear());
1324 int32_t eyear
= getGregorianYear();
1325 internalSet(UCAL_EXTENDED_YEAR
, eyear
);
1326 int32_t era
= GregorianCalendar::AD
;
1328 era
= GregorianCalendar::BC
;
1331 internalSet(UCAL_ERA
, era
);
1332 internalSet(UCAL_YEAR
, eyear
);
1334 // -------------------------------------
1337 void Calendar::roll(EDateFields field
, int32_t amount
, UErrorCode
& status
)
1339 roll((UCalendarDateFields
)field
, amount
, status
);
1342 void Calendar::roll(UCalendarDateFields field
, int32_t amount
, UErrorCode
& status
)
1345 return; // Nothing to do
1350 if(U_FAILURE(status
)) {
1354 case UCAL_DAY_OF_MONTH
:
1358 case UCAL_MILLISECOND
:
1359 case UCAL_MILLISECONDS_IN_DAY
:
1361 // These are the standard roll instructions. These work for all
1362 // simple cases, that is, cases in which the limits are fixed, such
1363 // as the hour, the day of the month, and the era.
1365 int32_t min
= getActualMinimum(field
,status
);
1366 int32_t max
= getActualMaximum(field
,status
);
1367 int32_t gap
= max
- min
+ 1;
1369 int32_t value
= internalGet(field
) + amount
;
1370 value
= (value
- min
) % gap
;
1381 case UCAL_HOUR_OF_DAY
:
1382 // Rolling the hour is difficult on the ONSET and CEASE days of
1383 // daylight savings. For example, if the change occurs at
1384 // 2 AM, we have the following progression:
1385 // ONSET: 12 Std -> 1 Std -> 3 Dst -> 4 Dst
1386 // CEASE: 12 Dst -> 1 Dst -> 1 Std -> 2 Std
1387 // To get around this problem we don't use fields; we manipulate
1388 // the time in millis directly.
1390 // Assume min == 0 in calculations below
1391 double start
= getTimeInMillis(status
);
1392 int32_t oldHour
= internalGet(field
);
1393 int32_t max
= getMaximum(field
);
1394 int32_t newHour
= (oldHour
+ amount
) % (max
+ 1);
1398 setTimeInMillis(start
+ kOneHour
* (newHour
- oldHour
),status
);
1403 // Rolling the month involves both pinning the final value
1404 // and adjusting the DAY_OF_MONTH if necessary. We only adjust the
1405 // DAY_OF_MONTH if, after updating the MONTH field, it is illegal.
1406 // E.g., <jan31>.roll(MONTH, 1) -> <feb28> or <feb29>.
1408 int32_t max
= getActualMaximum(UCAL_MONTH
, status
);
1409 int32_t mon
= (internalGet(UCAL_MONTH
) + amount
) % (max
+1);
1414 set(UCAL_MONTH
, mon
);
1416 // Keep the day of month in range. We don't want to spill over
1417 // into the next month; e.g., we don't want jan31 + 1 mo -> feb31 ->
1419 pinField(UCAL_DAY_OF_MONTH
,status
);
1425 case UCAL_EXTENDED_YEAR
:
1426 // Rolling the year can involve pinning the DAY_OF_MONTH.
1427 set(field
, internalGet(field
) + amount
);
1428 pinField(UCAL_MONTH
,status
);
1429 pinField(UCAL_DAY_OF_MONTH
,status
);
1432 case UCAL_WEEK_OF_MONTH
:
1434 // This is tricky, because during the roll we may have to shift
1435 // to a different day of the week. For example:
1441 // When rolling from the 6th or 7th back one week, we go to the
1442 // 1st (assuming that the first partial week counts). The same
1443 // thing happens at the end of the month.
1445 // The other tricky thing is that we have to figure out whether
1446 // the first partial week actually counts or not, based on the
1447 // minimal first days in the week. And we have to use the
1448 // correct first day of the week to delineate the week
1451 // Here's our algorithm. First, we find the real boundaries of
1452 // the month. Then we discard the first partial week if it
1453 // doesn't count in this locale. Then we fill in the ends with
1454 // phantom days, so that the first partial week and the last
1455 // partial week are full weeks. We then have a nice square
1456 // block of weeks. We do the usual rolling within this block,
1457 // as is done elsewhere in this method. If we wind up on one of
1458 // the phantom days that we added, we recognize this and pin to
1459 // the first or the last day of the month. Easy, eh?
1461 // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
1462 // in this locale. We have dow in 0..6.
1463 int32_t dow
= internalGet(UCAL_DAY_OF_WEEK
) - getFirstDayOfWeek();
1464 if (dow
< 0) dow
+= 7;
1466 // Find the day of the week (normalized for locale) for the first
1468 int32_t fdm
= (dow
- internalGet(UCAL_DAY_OF_MONTH
) + 1) % 7;
1469 if (fdm
< 0) fdm
+= 7;
1471 // Get the first day of the first full week of the month,
1472 // including phantom days, if any. Figure out if the first week
1473 // counts or not; if it counts, then fill in phantom days. If
1474 // not, advance to the first real full week (skip the partial week).
1476 if ((7 - fdm
) < getMinimalDaysInFirstWeek())
1477 start
= 8 - fdm
; // Skip the first partial week
1479 start
= 1 - fdm
; // This may be zero or negative
1481 // Get the day of the week (normalized for locale) for the last
1482 // day of the month.
1483 int32_t monthLen
= getActualMaximum(UCAL_DAY_OF_MONTH
, status
);
1484 int32_t ldm
= (monthLen
- internalGet(UCAL_DAY_OF_MONTH
) + dow
) % 7;
1485 // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here.
1487 // Get the limit day for the blocked-off rectangular month; that
1488 // is, the day which is one past the last day of the month,
1489 // after the month has already been filled in with phantom days
1490 // to fill out the last week. This day has a normalized DOW of 0.
1491 int32_t limit
= monthLen
+ 7 - ldm
;
1493 // Now roll between start and (limit - 1).
1494 int32_t gap
= limit
- start
;
1495 int32_t day_of_month
= (internalGet(UCAL_DAY_OF_MONTH
) + amount
*7 -
1497 if (day_of_month
< 0) day_of_month
+= gap
;
1498 day_of_month
+= start
;
1500 // Finally, pin to the real start and end of the month.
1501 if (day_of_month
< 1) day_of_month
= 1;
1502 if (day_of_month
> monthLen
) day_of_month
= monthLen
;
1504 // Set the DAY_OF_MONTH. We rely on the fact that this field
1505 // takes precedence over everything else (since all other fields
1506 // are also set at this point). If this fact changes (if the
1507 // disambiguation algorithm changes) then we will have to unset
1508 // the appropriate fields here so that DAY_OF_MONTH is attended
1510 set(UCAL_DAY_OF_MONTH
, day_of_month
);
1513 case UCAL_WEEK_OF_YEAR
:
1515 // This follows the outline of WEEK_OF_MONTH, except it applies
1516 // to the whole year. Please see the comment for WEEK_OF_MONTH
1517 // for general notes.
1519 // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
1520 // in this locale. We have dow in 0..6.
1521 int32_t dow
= internalGet(UCAL_DAY_OF_WEEK
) - getFirstDayOfWeek();
1522 if (dow
< 0) dow
+= 7;
1524 // Find the day of the week (normalized for locale) for the first
1526 int32_t fdy
= (dow
- internalGet(UCAL_DAY_OF_YEAR
) + 1) % 7;
1527 if (fdy
< 0) fdy
+= 7;
1529 // Get the first day of the first full week of the year,
1530 // including phantom days, if any. Figure out if the first week
1531 // counts or not; if it counts, then fill in phantom days. If
1532 // not, advance to the first real full week (skip the partial week).
1534 if ((7 - fdy
) < getMinimalDaysInFirstWeek())
1535 start
= 8 - fdy
; // Skip the first partial week
1537 start
= 1 - fdy
; // This may be zero or negative
1539 // Get the day of the week (normalized for locale) for the last
1541 int32_t yearLen
= getActualMaximum(UCAL_DAY_OF_YEAR
,status
);
1542 int32_t ldy
= (yearLen
- internalGet(UCAL_DAY_OF_YEAR
) + dow
) % 7;
1543 // We know yearLen >= DAY_OF_YEAR so we skip the += 7 step here.
1545 // Get the limit day for the blocked-off rectangular year; that
1546 // is, the day which is one past the last day of the year,
1547 // after the year has already been filled in with phantom days
1548 // to fill out the last week. This day has a normalized DOW of 0.
1549 int32_t limit
= yearLen
+ 7 - ldy
;
1551 // Now roll between start and (limit - 1).
1552 int32_t gap
= limit
- start
;
1553 int32_t day_of_year
= (internalGet(UCAL_DAY_OF_YEAR
) + amount
*7 -
1555 if (day_of_year
< 0) day_of_year
+= gap
;
1556 day_of_year
+= start
;
1558 // Finally, pin to the real start and end of the month.
1559 if (day_of_year
< 1) day_of_year
= 1;
1560 if (day_of_year
> yearLen
) day_of_year
= yearLen
;
1562 // Make sure that the year and day of year are attended to by
1563 // clearing other fields which would normally take precedence.
1564 // If the disambiguation algorithm is changed, this section will
1565 // have to be updated as well.
1566 set(UCAL_DAY_OF_YEAR
, day_of_year
);
1570 case UCAL_DAY_OF_YEAR
:
1572 // Roll the day of year using millis. Compute the millis for
1573 // the start of the year, and get the length of the year.
1574 double delta
= amount
* kOneDay
; // Scale up from days to millis
1575 double min2
= internalGet(UCAL_DAY_OF_YEAR
)-1;
1577 min2
= internalGetTime() - min2
;
1579 // double min2 = internalGetTime() - (internalGet(UCAL_DAY_OF_YEAR) - 1.0) * kOneDay;
1582 double yearLength
= getActualMaximum(UCAL_DAY_OF_YEAR
,status
);
1583 double oneYear
= yearLength
;
1585 newtime
= uprv_fmod((internalGetTime() + delta
- min2
), oneYear
);
1586 if (newtime
< 0) newtime
+= oneYear
;
1587 setTimeInMillis(newtime
+ min2
, status
);
1590 case UCAL_DAY_OF_WEEK
:
1591 case UCAL_DOW_LOCAL
:
1593 // Roll the day of week using millis. Compute the millis for
1594 // the start of the week, using the first day of week setting.
1595 // Restrict the millis to [start, start+7days).
1596 double delta
= amount
* kOneDay
; // Scale up from days to millis
1597 // Compute the number of days before the current day in this
1598 // week. This will be a value 0..6.
1599 int32_t leadDays
= internalGet(field
);
1600 leadDays
-= (field
== UCAL_DAY_OF_WEEK
) ? getFirstDayOfWeek() : 1;
1601 if (leadDays
< 0) leadDays
+= 7;
1602 double min2
= internalGetTime() - leadDays
* kOneDay
;
1603 double newtime
= uprv_fmod((internalGetTime() + delta
- min2
), kOneWeek
);
1604 if (newtime
< 0) newtime
+= kOneWeek
;
1605 setTimeInMillis(newtime
+ min2
, status
);
1608 case UCAL_DAY_OF_WEEK_IN_MONTH
:
1610 // Roll the day of week in the month using millis. Determine
1611 // the first day of the week in the month, and then the last,
1612 // and then roll within that range.
1613 double delta
= amount
* kOneWeek
; // Scale up from weeks to millis
1614 // Find the number of same days of the week before this one
1616 int32_t preWeeks
= (internalGet(UCAL_DAY_OF_MONTH
) - 1) / 7;
1617 // Find the number of same days of the week after this one
1619 int32_t postWeeks
= (getActualMaximum(UCAL_DAY_OF_MONTH
,status
) -
1620 internalGet(UCAL_DAY_OF_MONTH
)) / 7;
1621 // From these compute the min and gap millis for rolling.
1622 double min2
= internalGetTime() - preWeeks
* kOneWeek
;
1623 double gap2
= kOneWeek
* (preWeeks
+ postWeeks
+ 1); // Must add 1!
1624 // Roll within this range
1625 double newtime
= uprv_fmod((internalGetTime() + delta
- min2
), gap2
);
1626 if (newtime
< 0) newtime
+= gap2
;
1627 setTimeInMillis(newtime
+ min2
, status
);
1630 case UCAL_JULIAN_DAY
:
1631 set(field
, internalGet(field
) + amount
);
1634 // Other fields cannot be rolled by this method
1635 #if defined (U_DEBUG_CAL)
1636 fprintf(stderr
, "%s:%d: ILLEGAL ARG because of roll on non-rollable field %s\n",
1637 __FILE__
, __LINE__
,fldName(field
));
1639 status
= U_ILLEGAL_ARGUMENT_ERROR
;
1643 void Calendar::add(EDateFields field
, int32_t amount
, UErrorCode
& status
)
1645 Calendar::add((UCalendarDateFields
)field
, amount
, status
);
1648 // -------------------------------------
1649 void Calendar::add(UCalendarDateFields field
, int32_t amount
, UErrorCode
& status
)
1652 return; // Do nothing!
1655 // We handle most fields in the same way. The algorithm is to add
1656 // a computed amount of millis to the current millis. The only
1657 // wrinkle is with DST -- for some fields, like the DAY_OF_MONTH,
1658 // we don't want the HOUR to shift due to changes in DST. If the
1659 // result of the add operation is to move from DST to Standard, or
1660 // vice versa, we need to adjust by an hour forward or back,
1661 // respectively. For such fields we set keepHourInvariant to TRUE.
1663 // We only adjust the DST for fields larger than an hour. For
1664 // fields smaller than an hour, we cannot adjust for DST without
1665 // causing problems. for instance, if you add one hour to April 5,
1666 // 1998, 1:00 AM, in PST, the time becomes "2:00 AM PDT" (an
1667 // illegal value), but then the adjustment sees the change and
1668 // compensates by subtracting an hour. As a result the time
1669 // doesn't advance at all.
1671 // For some fields larger than a day, such as a UCAL_MONTH, we pin the
1672 // UCAL_DAY_OF_MONTH. This allows <March 31>.add(UCAL_MONTH, 1) to be
1673 // <April 30>, rather than <April 31> => <May 1>.
1675 double delta
= amount
; // delta in ms
1676 UBool keepHourInvariant
= TRUE
;
1680 set(field
, get(field
, status
) + amount
);
1681 pinField(UCAL_ERA
, status
);
1685 case UCAL_EXTENDED_YEAR
:
1688 set(field
, get(field
, status
) + amount
);
1689 pinField(UCAL_DAY_OF_MONTH
, status
);
1692 case UCAL_WEEK_OF_YEAR
:
1693 case UCAL_WEEK_OF_MONTH
:
1694 case UCAL_DAY_OF_WEEK_IN_MONTH
:
1699 delta
*= 12 * kOneHour
;
1702 case UCAL_DAY_OF_MONTH
:
1703 case UCAL_DAY_OF_YEAR
:
1704 case UCAL_DAY_OF_WEEK
:
1705 case UCAL_DOW_LOCAL
:
1706 case UCAL_JULIAN_DAY
:
1710 case UCAL_HOUR_OF_DAY
:
1713 keepHourInvariant
= FALSE
;
1717 delta
*= kOneMinute
;
1718 keepHourInvariant
= FALSE
;
1722 delta
*= kOneSecond
;
1723 keepHourInvariant
= FALSE
;
1726 case UCAL_MILLISECOND
:
1727 case UCAL_MILLISECONDS_IN_DAY
:
1728 keepHourInvariant
= FALSE
;
1732 #if defined (U_DEBUG_CAL)
1733 fprintf(stderr
, "%s:%d: ILLEGAL ARG because field %s not addable",
1734 __FILE__
, __LINE__
, fldName(field
));
1736 status
= U_ILLEGAL_ARGUMENT_ERROR
;
1738 // throw new IllegalArgumentException("Calendar.add(" + fieldName(field) +
1739 // ") not supported");
1742 // In order to keep the hour invariant (for fields where this is
1743 // appropriate), record the DST_OFFSET before and after the add()
1744 // operation. If it has changed, then adjust the millis to
1748 if (keepHourInvariant
) {
1749 dst
= get(UCAL_DST_OFFSET
, status
);
1750 hour
= internalGet(UCAL_HOUR_OF_DAY
);
1753 setTimeInMillis(getTimeInMillis(status
) + delta
, status
);
1755 if (keepHourInvariant
) {
1756 dst
-= get(UCAL_DST_OFFSET
, status
);
1758 // We have done an hour-invariant adjustment but the
1759 // DST offset has altered. We adjust millis to keep
1760 // the hour constant. In cases such as midnight after
1761 // a DST change which occurs at midnight, there is the
1762 // danger of adjusting into a different day. To avoid
1763 // this we make the adjustment only if it actually
1764 // maintains the hour.
1765 double t
= internalGetTime();
1766 setTimeInMillis(t
+ dst
, status
);
1767 if (get(UCAL_HOUR_OF_DAY
, status
) != hour
) {
1768 setTimeInMillis(t
, status
);
1774 // -------------------------------------
1775 int32_t Calendar::fieldDifference(UDate when
, EDateFields field
, UErrorCode
& status
) {
1776 return fieldDifference(when
, (UCalendarDateFields
) field
, status
);
1779 int32_t Calendar::fieldDifference(UDate targetMs
, UCalendarDateFields field
, UErrorCode
& ec
) {
1780 if (U_FAILURE(ec
)) return 0;
1782 double startMs
= getTimeInMillis(ec
);
1783 // Always add from the start millis. This accomodates
1784 // operations like adding years from February 29, 2000 up to
1785 // February 29, 2004. If 1, 1, 1, 1 is added to the year
1786 // field, the DOM gets pinned to 28 and stays there, giving an
1787 // incorrect DOM difference of 1. We have to add 1, reset, 2,
1788 // reset, 3, reset, 4.
1789 if (startMs
< targetMs
) {
1791 // Find a value that is too large
1792 while (U_SUCCESS(ec
)) {
1793 setTimeInMillis(startMs
, ec
);
1794 add(field
, max
, ec
);
1795 double ms
= getTimeInMillis(ec
);
1796 if (ms
== targetMs
) {
1798 } else if (ms
> targetMs
) {
1803 // Field difference too large to fit into int32_t
1804 #if defined (U_DEBUG_CAL)
1805 fprintf(stderr
, "%s:%d: ILLEGAL ARG because field %s's max too large for int32_t\n",
1806 __FILE__
, __LINE__
, fldName(field
));
1808 ec
= U_ILLEGAL_ARGUMENT_ERROR
;
1812 // Do a binary search
1813 while ((max
- min
) > 1 && U_SUCCESS(ec
)) {
1814 int32_t t
= (min
+ max
) / 2;
1815 setTimeInMillis(startMs
, ec
);
1817 double ms
= getTimeInMillis(ec
);
1818 if (ms
== targetMs
) {
1820 } else if (ms
> targetMs
) {
1826 } else if (startMs
> targetMs
) {
1828 // Find a value that is too small
1829 while (U_SUCCESS(ec
)) {
1830 setTimeInMillis(startMs
, ec
);
1831 add(field
, max
, ec
);
1832 double ms
= getTimeInMillis(ec
);
1833 if (ms
== targetMs
) {
1835 } else if (ms
< targetMs
) {
1840 // Field difference too large to fit into int32_t
1841 #if defined (U_DEBUG_CAL)
1842 fprintf(stderr
, "%s:%d: ILLEGAL ARG because field %s's max too large for int32_t\n",
1843 __FILE__
, __LINE__
, fldName(field
));
1845 ec
= U_ILLEGAL_ARGUMENT_ERROR
;
1849 // Do a binary search
1850 while ((min
- max
) > 1 && U_SUCCESS(ec
)) {
1851 int32_t t
= (min
+ max
) / 2;
1852 setTimeInMillis(startMs
, ec
);
1854 double ms
= getTimeInMillis(ec
);
1855 if (ms
== targetMs
) {
1857 } else if (ms
< targetMs
) {
1864 // Set calendar to end point
1865 setTimeInMillis(startMs
, ec
);
1866 add(field
, min
, ec
);
1868 /* Test for buffer overflows */
1875 // -------------------------------------
1878 Calendar::adoptTimeZone(TimeZone
* zone
)
1880 // Do nothing if passed-in zone is NULL
1881 if (zone
== NULL
) return;
1883 // fZone should always be non-null
1884 if (fZone
!= NULL
) delete fZone
;
1887 // if the zone changes, we need to recompute the time fields
1888 fAreFieldsSet
= FALSE
;
1891 // -------------------------------------
1893 Calendar::setTimeZone(const TimeZone
& zone
)
1895 adoptTimeZone(zone
.clone());
1898 // -------------------------------------
1901 Calendar::getTimeZone() const
1906 // -------------------------------------
1909 Calendar::orphanTimeZone()
1911 TimeZone
*z
= fZone
;
1912 // we let go of the time zone; the new time zone is the system default time zone
1913 fZone
= TimeZone::createDefault();
1917 // -------------------------------------
1920 Calendar::setLenient(UBool lenient
)
1925 // -------------------------------------
1928 Calendar::isLenient() const
1933 // -------------------------------------
1936 Calendar::setFirstDayOfWeek(UCalendarDaysOfWeek value
)
1938 if (fFirstDayOfWeek
!= value
&&
1939 value
>= UCAL_SUNDAY
&& value
<= UCAL_SATURDAY
) {
1940 fFirstDayOfWeek
= value
;
1941 fAreFieldsSet
= FALSE
;
1945 // -------------------------------------
1947 Calendar::EDaysOfWeek
1948 Calendar::getFirstDayOfWeek() const
1950 return (Calendar::EDaysOfWeek
)fFirstDayOfWeek
;
1954 Calendar::getFirstDayOfWeek(UErrorCode
& /*status*/) const
1956 return fFirstDayOfWeek
;
1958 // -------------------------------------
1961 Calendar::setMinimalDaysInFirstWeek(uint8_t value
)
1963 // Values less than 1 have the same effect as 1; values greater
1964 // than 7 have the same effect as 7. However, we normalize values
1965 // so operator== and so forth work.
1968 } else if (value
> 7) {
1971 if (fMinimalDaysInFirstWeek
!= value
) {
1972 fMinimalDaysInFirstWeek
= value
;
1973 fAreFieldsSet
= FALSE
;
1977 // -------------------------------------
1980 Calendar::getMinimalDaysInFirstWeek() const
1982 return fMinimalDaysInFirstWeek
;
1985 // ------------------------------------- limits
1988 Calendar::getMinimum(EDateFields field
) const {
1989 return getLimit((UCalendarDateFields
) field
,UCAL_LIMIT_MINIMUM
);
1993 Calendar::getMinimum(UCalendarDateFields field
) const
1995 return getLimit(field
,UCAL_LIMIT_MINIMUM
);
1998 // -------------------------------------
2000 Calendar::getMaximum(EDateFields field
) const
2002 return getLimit((UCalendarDateFields
) field
,UCAL_LIMIT_MAXIMUM
);
2006 Calendar::getMaximum(UCalendarDateFields field
) const
2008 return getLimit(field
,UCAL_LIMIT_MAXIMUM
);
2011 // -------------------------------------
2013 Calendar::getGreatestMinimum(EDateFields field
) const
2015 return getLimit((UCalendarDateFields
)field
,UCAL_LIMIT_GREATEST_MINIMUM
);
2019 Calendar::getGreatestMinimum(UCalendarDateFields field
) const
2021 return getLimit(field
,UCAL_LIMIT_GREATEST_MINIMUM
);
2024 // -------------------------------------
2026 Calendar::getLeastMaximum(EDateFields field
) const
2028 return getLimit((UCalendarDateFields
) field
,UCAL_LIMIT_LEAST_MAXIMUM
);
2032 Calendar::getLeastMaximum(UCalendarDateFields field
) const
2034 return getLimit( field
,UCAL_LIMIT_LEAST_MAXIMUM
);
2037 // -------------------------------------
2039 Calendar::getActualMinimum(EDateFields field
, UErrorCode
& status
) const
2041 return getActualMinimum((UCalendarDateFields
) field
, status
);
2044 int32_t Calendar::getLimit(UCalendarDateFields field
, ELimitType limitType
) const {
2046 case UCAL_DAY_OF_WEEK
:
2049 case UCAL_HOUR_OF_DAY
:
2052 case UCAL_MILLISECOND
:
2053 case UCAL_ZONE_OFFSET
:
2054 case UCAL_DST_OFFSET
:
2055 case UCAL_DOW_LOCAL
:
2056 case UCAL_JULIAN_DAY
:
2057 case UCAL_MILLISECONDS_IN_DAY
:
2058 return kCalendarLimits
[field
][limitType
];
2060 return handleGetLimit(field
, limitType
);
2066 Calendar::getActualMinimum(UCalendarDateFields field
, UErrorCode
& status
) const
2068 int32_t fieldValue
= getGreatestMinimum(field
);
2069 int32_t endValue
= getMinimum(field
);
2071 // if we know that the minimum value is always the same, just return it
2072 if (fieldValue
== endValue
) {
2076 // clone the calendar so we don't mess with the real one, and set it to
2077 // accept anything for the field values
2078 Calendar
*work
= (Calendar
*)this->clone();
2079 work
->setLenient(TRUE
);
2081 // now try each value from getLeastMaximum() to getMaximum() one by one until
2082 // we get a value that normalizes to another value. The last value that
2083 // normalizes to itself is the actual minimum for the current date
2084 int32_t result
= fieldValue
;
2087 work
->set(field
, fieldValue
);
2088 if (work
->get(field
, status
) != fieldValue
) {
2092 result
= fieldValue
;
2095 } while (fieldValue
>= endValue
);
2099 /* Test for buffer overflows */
2100 if(U_FAILURE(status
)) {
2106 // -------------------------------------
2111 * Ensure that each field is within its valid range by calling {@link
2112 * #validateField(int)} on each field that has been set. This method
2113 * should only be called if this calendar is not lenient.
2115 * @see #validateField(int)
2118 void Calendar::validateFields(UErrorCode
&status
) {
2119 for (int32_t field
= 0; U_SUCCESS(status
) && (field
< UCAL_FIELD_COUNT
); field
++) {
2120 if (isSet((UCalendarDateFields
)field
)) {
2121 validateField((UCalendarDateFields
)field
, status
);
2127 * Validate a single field of this calendar. Subclasses should
2128 * override this method to validate any calendar-specific fields.
2129 * Generic fields can be handled by
2130 * <code>Calendar.validateField()</code>.
2131 * @see #validateField(int, int, int)
2134 void Calendar::validateField(UCalendarDateFields field
, UErrorCode
&status
) {
2137 case UCAL_DAY_OF_MONTH
:
2138 y
= handleGetExtendedYear();
2139 validateField(field
, 1, handleGetMonthLength(y
, internalGet(UCAL_MONTH
)), status
);
2141 case UCAL_DAY_OF_YEAR
:
2142 y
= handleGetExtendedYear();
2143 validateField(field
, 1, handleGetYearLength(y
), status
);
2145 case UCAL_DAY_OF_WEEK_IN_MONTH
:
2146 if (internalGet(field
) == 0) {
2147 #if defined (U_DEBUG_CAL)
2148 fprintf(stderr
, "%s:%d: ILLEGAL ARG because DOW in month cannot be 0\n",
2149 __FILE__
, __LINE__
);
2151 status
= U_ILLEGAL_ARGUMENT_ERROR
; // "DAY_OF_WEEK_IN_MONTH cannot be zero"
2154 validateField(field
, getMinimum(field
), getMaximum(field
), status
);
2157 validateField(field
, getMinimum(field
), getMaximum(field
), status
);
2163 * Validate a single field of this calendar given its minimum and
2164 * maximum allowed value. If the field is out of range, throw a
2165 * descriptive <code>IllegalArgumentException</code>. Subclasses may
2166 * use this method in their implementation of {@link
2167 * #validateField(int)}.
2170 void Calendar::validateField(UCalendarDateFields field
, int32_t min
, int32_t max
, UErrorCode
& status
)
2172 int32_t value
= fFields
[field
];
2173 if (value
< min
|| value
> max
) {
2174 #if defined (U_DEBUG_CAL)
2175 fprintf(stderr
, "%s:%d: ILLEGAL ARG because of field %s out of range %d..%d at %d\n",
2176 __FILE__
, __LINE__
,fldName(field
),min
,max
,value
);
2178 status
= U_ILLEGAL_ARGUMENT_ERROR
;
2183 // -------------------------
2185 const UFieldResolutionTable
* Calendar::getFieldResolutionTable() const {
2186 return kDatePrecedence
;
2190 UCalendarDateFields
Calendar::newerField(UCalendarDateFields defaultField
, UCalendarDateFields alternateField
) const
2192 if (fStamp
[alternateField
] > fStamp
[defaultField
]) {
2193 return alternateField
;
2195 return defaultField
;
2198 UCalendarDateFields
Calendar::resolveFields(const UFieldResolutionTable
* precedenceTable
) {
2199 int32_t bestField
= UCAL_FIELD_COUNT
;
2200 for (int32_t g
=0; precedenceTable
[g
][0][0] != -1 && (bestField
== UCAL_FIELD_COUNT
); ++g
) {
2201 int32_t bestStamp
= kUnset
;
2202 for (int32_t l
=0; precedenceTable
[g
][l
][0] != -1; ++l
) {
2203 int32_t lineStamp
= kUnset
;
2204 // Skip over first entry if it is negative
2205 for (int32_t i
=((precedenceTable
[g
][l
][0]>=kResolveRemap
)?1:0); precedenceTable
[g
][l
][i
]!=-1; ++i
) {
2206 int32_t s
= fStamp
[precedenceTable
[g
][l
][i
]];
2207 // If any field is unset then don't use this line
2210 } else if(s
> lineStamp
) {
2214 // Record new maximum stamp & field no.
2215 if (lineStamp
> bestStamp
) {
2216 bestStamp
= lineStamp
;
2217 bestField
= precedenceTable
[g
][l
][0]; // First field refers to entire line
2223 return (UCalendarDateFields
)( (bestField
>=kResolveRemap
)?(bestField
&(kResolveRemap
-1)):bestField
);
2226 const UFieldResolutionTable
Calendar::kDatePrecedence
[] =
2229 { UCAL_DAY_OF_MONTH
, kResolveSTOP
},
2230 { UCAL_WEEK_OF_YEAR
, UCAL_DAY_OF_WEEK
, kResolveSTOP
},
2231 { UCAL_WEEK_OF_MONTH
, UCAL_DAY_OF_WEEK
, kResolveSTOP
},
2232 { UCAL_DAY_OF_WEEK_IN_MONTH
, UCAL_DAY_OF_WEEK
, kResolveSTOP
},
2233 { UCAL_WEEK_OF_YEAR
, UCAL_DOW_LOCAL
, kResolveSTOP
},
2234 { UCAL_WEEK_OF_MONTH
, UCAL_DOW_LOCAL
, kResolveSTOP
},
2235 { UCAL_DAY_OF_WEEK_IN_MONTH
, UCAL_DOW_LOCAL
, kResolveSTOP
},
2236 { UCAL_DAY_OF_YEAR
, kResolveSTOP
},
2237 { kResolveRemap
| UCAL_DAY_OF_MONTH
, UCAL_YEAR
, kResolveSTOP
}, // if YEAR is set over YEAR_WOY use DAY_OF_MONTH
2238 { kResolveRemap
| UCAL_WEEK_OF_YEAR
, UCAL_YEAR_WOY
, kResolveSTOP
}, // if YEAR_WOY is set, calc based on WEEK_OF_YEAR
2242 { UCAL_WEEK_OF_YEAR
, kResolveSTOP
},
2243 { UCAL_WEEK_OF_MONTH
, kResolveSTOP
},
2244 { UCAL_DAY_OF_WEEK_IN_MONTH
, kResolveSTOP
},
2245 { kResolveRemap
| UCAL_DAY_OF_WEEK_IN_MONTH
, UCAL_DAY_OF_WEEK
, kResolveSTOP
},
2246 { kResolveRemap
| UCAL_DAY_OF_WEEK_IN_MONTH
, UCAL_DOW_LOCAL
, kResolveSTOP
},
2253 const UFieldResolutionTable
Calendar::kDOWPrecedence
[] =
2256 { UCAL_DAY_OF_WEEK
,kResolveSTOP
, kResolveSTOP
},
2257 { UCAL_DOW_LOCAL
,kResolveSTOP
, kResolveSTOP
},
2263 // precedence for calculating a year
2264 const UFieldResolutionTable
Calendar::kYearPrecedence
[] =
2267 { UCAL_YEAR
, kResolveSTOP
},
2268 { UCAL_EXTENDED_YEAR
, kResolveSTOP
},
2269 { UCAL_YEAR_WOY
, UCAL_WEEK_OF_YEAR
, kResolveSTOP
}, // YEAR_WOY is useless without WEEK_OF_YEAR
2276 // -------------------------
2279 void Calendar::computeTime(UErrorCode
& status
) {
2281 validateFields(status
);
2284 // Compute the Julian day
2285 int32_t julianDay
= computeJulianDay();
2287 double millis
= Grego::julianDayToMillis(julianDay
);
2289 #if defined (U_DEBUG_CAL)
2290 // int32_t julianInsanityCheck = (int32_t)Math::floorDivide(millis, kOneDay);
2291 // julianInsanityCheck += kEpochStartAsJulianDay;
2292 // if(1 || julianInsanityCheck != julianDay) {
2293 // fprintf(stderr, "%s:%d- D'oh- computed jules %d, to mills (%s)%.lf, recomputed %d\n",
2294 // __FILE__, __LINE__, julianDay, millis<0.0?"NEG":"", millis, julianInsanityCheck);
2298 int32_t millisInDay
;
2300 // We only use MILLISECONDS_IN_DAY if it has been set by the user.
2301 // This makes it possible for the caller to set the calendar to a
2302 // time and call clear(MONTH) to reset the MONTH to January. This
2303 // is legacy behavior. Without this, clear(MONTH) has no effect,
2304 // since the internally set JULIAN_DAY is used.
2305 if (fStamp
[UCAL_MILLISECONDS_IN_DAY
] >= ((int32_t)kMinimumUserStamp
) &&
2306 newestStamp(UCAL_AM_PM
, UCAL_MILLISECOND
, kUnset
) <= fStamp
[UCAL_MILLISECONDS_IN_DAY
]) {
2307 millisInDay
= internalGet(UCAL_MILLISECONDS_IN_DAY
);
2309 millisInDay
= computeMillisInDay();
2312 // Compute the time zone offset and DST offset. There are two potential
2313 // ambiguities here. We'll assume a 2:00 am (wall time) switchover time
2314 // for discussion purposes here.
2315 // 1. The transition into DST. Here, a designated time of 2:00 am - 2:59 am
2316 // can be in standard or in DST depending. However, 2:00 am is an invalid
2317 // representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST).
2318 // We assume standard time.
2319 // 2. The transition out of DST. Here, a designated time of 1:00 am - 1:59 am
2320 // can be in standard or DST. Both are valid representations (the rep
2321 // jumps from 1:59:59 DST to 1:00:00 Std).
2322 // Again, we assume standard time.
2323 // We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET
2324 // or DST_OFFSET fields; then we use those fields.
2325 if (fStamp
[UCAL_ZONE_OFFSET
] >= ((int32_t)kMinimumUserStamp
) ||
2326 fStamp
[UCAL_DST_OFFSET
] >= ((int32_t)kMinimumUserStamp
)) {
2327 millisInDay
-= internalGet(UCAL_ZONE_OFFSET
) + internalGet(UCAL_DST_OFFSET
);
2329 millisInDay
-= computeZoneOffset(millis
, millisInDay
,status
);
2332 internalSetTime(millis
+ millisInDay
);
2336 * Compute the milliseconds in the day from the fields. This is a
2337 * value from 0 to 23:59:59.999 inclusive, unless fields are out of
2338 * range, in which case it can be an arbitrary value. This value
2339 * reflects local zone wall time.
2342 int32_t Calendar::computeMillisInDay() {
2343 // Do the time portion of the conversion.
2345 int32_t millisInDay
= 0;
2347 // Find the best set of fields specifying the time of day. There
2348 // are only two possibilities here; the HOUR_OF_DAY or the
2349 // AM_PM and the HOUR.
2350 int32_t hourOfDayStamp
= fStamp
[UCAL_HOUR_OF_DAY
];
2351 int32_t hourStamp
= (fStamp
[UCAL_HOUR
] > fStamp
[UCAL_AM_PM
])?fStamp
[UCAL_HOUR
]:fStamp
[UCAL_AM_PM
];
2352 int32_t bestStamp
= (hourStamp
> hourOfDayStamp
) ? hourStamp
: hourOfDayStamp
;
2355 if (bestStamp
!= kUnset
) {
2356 if (bestStamp
== hourOfDayStamp
) {
2357 // Don't normalize here; let overflow bump into the next period.
2358 // This is consistent with how we handle other fields.
2359 millisInDay
+= internalGet(UCAL_HOUR_OF_DAY
);
2361 // Don't normalize here; let overflow bump into the next period.
2362 // This is consistent with how we handle other fields.
2363 millisInDay
+= internalGet(UCAL_HOUR
);
2364 millisInDay
+= 12 * internalGet(UCAL_AM_PM
); // Default works for unset AM_PM
2368 // We use the fact that unset == 0; we start with millisInDay
2371 millisInDay
+= internalGet(UCAL_MINUTE
); // now have minutes
2373 millisInDay
+= internalGet(UCAL_SECOND
); // now have seconds
2374 millisInDay
*= 1000;
2375 millisInDay
+= internalGet(MILLISECOND
); // now have millis
2381 * This method can assume EXTENDED_YEAR has been set.
2382 * @param millis milliseconds of the date fields
2383 * @param millisInDay milliseconds of the time fields; may be out
2387 int32_t Calendar::computeZoneOffset(double millis
, int32_t millisInDay
, UErrorCode
&ec
) {
2388 int32_t rawOffset
, dstOffset
;
2389 getTimeZone().getOffset(millis
+millisInDay
, TRUE
, rawOffset
, dstOffset
, ec
);
2390 return rawOffset
+ dstOffset
;
2391 // Note: Because we pass in wall millisInDay, rather than
2392 // standard millisInDay, we interpret "1:00 am" on the day
2393 // of cessation of DST as "1:00 am Std" (assuming the time
2394 // of cessation is 2:00 am).
2397 int32_t Calendar::computeJulianDay()
2399 // We want to see if any of the date fields is newer than the
2400 // JULIAN_DAY. If not, then we use JULIAN_DAY. If so, then we do
2401 // the normal resolution. We only use JULIAN_DAY if it has been
2402 // set by the user. This makes it possible for the caller to set
2403 // the calendar to a time and call clear(MONTH) to reset the MONTH
2404 // to January. This is legacy behavior. Without this,
2405 // clear(MONTH) has no effect, since the internally set JULIAN_DAY
2407 if (fStamp
[UCAL_JULIAN_DAY
] >= (int32_t)kMinimumUserStamp
) {
2408 int32_t bestStamp
= newestStamp(UCAL_ERA
, UCAL_DAY_OF_WEEK_IN_MONTH
, kUnset
);
2409 bestStamp
= newestStamp(UCAL_YEAR_WOY
, UCAL_EXTENDED_YEAR
, bestStamp
);
2410 if (bestStamp
<= fStamp
[UCAL_JULIAN_DAY
]) {
2411 return internalGet(UCAL_JULIAN_DAY
);
2415 UCalendarDateFields bestField
= resolveFields(getFieldResolutionTable());
2416 if (bestField
== UCAL_FIELD_COUNT
) {
2417 bestField
= UCAL_DAY_OF_MONTH
;
2420 return handleComputeJulianDay(bestField
);
2423 // -------------------------------------------
2425 int32_t Calendar::handleComputeJulianDay(UCalendarDateFields bestField
) {
2426 UBool useMonth
= (bestField
== UCAL_DAY_OF_MONTH
||
2427 bestField
== UCAL_WEEK_OF_MONTH
||
2428 bestField
== UCAL_DAY_OF_WEEK_IN_MONTH
);
2431 if (bestField
== UCAL_WEEK_OF_YEAR
) {
2432 year
= internalGet(UCAL_YEAR_WOY
, handleGetExtendedYear());
2433 internalSet(UCAL_EXTENDED_YEAR
, year
);
2435 year
= handleGetExtendedYear();
2436 internalSet(UCAL_EXTENDED_YEAR
, year
);
2439 #if defined (U_DEBUG_CAL)
2440 fprintf(stderr
, "%s:%d - bf= %s - y=%d\n", __FILE__
, __LINE__
, fldName(bestField
), year
);
2443 // Get the Julian day of the day BEFORE the start of this year.
2444 // If useMonth is true, get the day before the start of the month.
2446 // give calendar subclass a chance to have a default 'first' month
2449 if(isSet(UCAL_MONTH
)) {
2450 month
= (int8_t)internalGet(UCAL_MONTH
);
2452 month
= (int8_t)getDefaultMonthInYear();
2455 int32_t julianDay
= handleComputeMonthStart(year
, useMonth
? month
: 0, useMonth
);
2457 if (bestField
== UCAL_DAY_OF_MONTH
) {
2459 // give calendar subclass a chance to have a default 'first' dom
2461 if(isSet(UCAL_DAY_OF_MONTH
)) {
2462 dayOfMonth
= internalGet(UCAL_DAY_OF_MONTH
,1);
2464 dayOfMonth
= getDefaultDayInMonth(month
);
2466 return julianDay
+ dayOfMonth
;
2469 if (bestField
== UCAL_DAY_OF_YEAR
) {
2470 return julianDay
+ internalGet(UCAL_DAY_OF_YEAR
);
2473 int32_t firstDayOfWeek
= getFirstDayOfWeek(); // Localized fdw
2475 // At this point julianDay is the 0-based day BEFORE the first day of
2476 // January 1, year 1 of the given calendar. If julianDay == 0, it
2477 // specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
2478 // or Gregorian). (or it is before the month we are in, if useMonth is True)
2480 // At this point we need to process the WEEK_OF_MONTH or
2481 // WEEK_OF_YEAR, which are similar, or the DAY_OF_WEEK_IN_MONTH.
2482 // First, perform initial shared computations. These locate the
2483 // first week of the period.
2485 // Get the 0-based localized DOW of day one of the month or year.
2486 // Valid range 0..6.
2487 int32_t first
= julianDayToDayOfWeek(julianDay
+ 1) - firstDayOfWeek
;
2492 int32_t dowLocal
= getLocalDOW();
2494 // Find the first target DOW (dowLocal) in the month or year.
2495 // Actually, it may be just before the first of the month or year.
2496 // It will be an integer from -5..7.
2497 int32_t date
= 1 - first
+ dowLocal
;
2499 if (bestField
== UCAL_DAY_OF_WEEK_IN_MONTH
) {
2500 // Adjust the target DOW to be in the month or year.
2505 // The only trickiness occurs if the day-of-week-in-month is
2507 int32_t dim
= internalGet(UCAL_DAY_OF_WEEK_IN_MONTH
, 1);
2509 date
+= 7*(dim
- 1);
2512 // Move date to the last of this day-of-week in this month,
2513 // then back up as needed. If dim==-1, we don't back up at
2514 // all. If dim==-2, we back up once, etc. Don't back up
2515 // past the first of the given day-of-week in this month.
2516 // Note that we handle -2, -3, etc. correctly, even though
2517 // values < -1 are technically disallowed.
2518 int32_t m
= internalGet(UCAL_MONTH
, UCAL_JANUARY
);
2519 int32_t monthLength
= handleGetMonthLength(year
, m
);
2520 date
+= ((monthLength
- date
) / 7 + dim
+ 1) * 7;
2523 #if defined (U_DEBUG_CAL)
2524 fprintf(stderr
, "%s:%d - bf= %s\n", __FILE__
, __LINE__
, fldName(bestField
));
2527 if(bestField
== UCAL_WEEK_OF_YEAR
) { // ------------------------------------- WOY -------------
2528 if(!isSet(UCAL_YEAR_WOY
) || // YWOY not set at all or
2529 ( (resolveFields(kYearPrecedence
) != UCAL_YEAR_WOY
) // YWOY doesn't have precedence
2530 && (fStamp
[UCAL_YEAR_WOY
]!=kInternallySet
) ) ) { // (excluding where all fields are internally set - then YWOY is used)
2531 // need to be sure to stay in 'real' year.
2532 int32_t woy
= internalGet(bestField
);
2534 int32_t nextJulianDay
= handleComputeMonthStart(year
+1, 0, FALSE
); // jd of day before jan 1
2535 int32_t nextFirst
= julianDayToDayOfWeek(nextJulianDay
+ 1) - firstDayOfWeek
;
2537 if (nextFirst
< 0) { // 0..6 ldow of Jan 1
2541 if(woy
==1) { // FIRST WEEK ---------------------------------
2542 #if defined (U_DEBUG_CAL)
2543 fprintf(stderr
, "%s:%d - woy=%d, yp=%d, nj(%d)=%d, nf=%d", __FILE__
, __LINE__
,
2544 internalGet(bestField
), resolveFields(kYearPrecedence
), year
+1,
2545 nextJulianDay
, nextFirst
);
2547 fprintf(stderr
, " next: %d DFW, min=%d \n", (7-nextFirst
), getMinimalDaysInFirstWeek() );
2550 // nextFirst is now the localized DOW of Jan 1 of y-woy+1
2551 if((nextFirst
> 0) && // Jan 1 starts on FDOW
2552 (7-nextFirst
) >= getMinimalDaysInFirstWeek()) { // or enough days in the week
2553 // Jan 1 of (yearWoy+1) is in yearWoy+1 - recalculate JD to next year
2554 #if defined (U_DEBUG_CAL)
2555 fprintf(stderr
, "%s:%d - was going to move JD from %d to %d [d%d]\n", __FILE__
, __LINE__
,
2556 julianDay
, nextJulianDay
, (nextJulianDay
-julianDay
));
2558 julianDay
= nextJulianDay
;
2560 // recalculate 'first' [0-based local dow of jan 1]
2561 first
= julianDayToDayOfWeek(julianDay
+ 1) - firstDayOfWeek
;
2565 // recalculate date.
2566 date
= 1 - first
+ dowLocal
;
2568 } else if(woy
>=getLeastMaximum(bestField
)) {
2569 // could be in the last week- find out if this JD would overstep
2570 int32_t testDate
= date
;
2571 if ((7 - first
) < getMinimalDaysInFirstWeek()) {
2575 // Now adjust for the week number.
2576 testDate
+= 7 * (woy
- 1);
2578 #if defined (U_DEBUG_CAL)
2579 fprintf(stderr
, "%s:%d - y=%d, y-1=%d doy%d, njd%d (C.F. %d)\n",
2580 __FILE__
, __LINE__
, year
, year
-1, testDate
, julianDay
+testDate
, nextJulianDay
);
2582 if(julianDay
+testDate
> nextJulianDay
) { // is it past Dec 31? (nextJulianDay is day BEFORE year+1's Jan 1)
2583 // Fire up the calculating engines.. retry YWOY = (year-1)
2584 julianDay
= handleComputeMonthStart(year
-1, 0, FALSE
); // jd before Jan 1 of previous year
2585 first
= julianDayToDayOfWeek(julianDay
+ 1) - firstDayOfWeek
; // 0 based local dow of first week
2587 if(first
< 0) { // 0..6
2590 date
= 1 - first
+ dowLocal
;
2592 #if defined (U_DEBUG_CAL)
2593 fprintf(stderr
, "%s:%d - date now %d, jd%d, ywoy%d\n",
2594 __FILE__
, __LINE__
, date
, julianDay
, year
-1);
2598 } /* correction needed */
2599 } /* leastmaximum */
2600 } /* resolvefields(year) != year_woy */
2601 } /* bestfield != week_of_year */
2603 // assert(bestField == WEEK_OF_MONTH || bestField == WEEK_OF_YEAR)
2604 // Adjust for minimal days in first week
2605 if ((7 - first
) < getMinimalDaysInFirstWeek()) {
2609 // Now adjust for the week number.
2610 date
+= 7 * (internalGet(bestField
) - 1);
2613 return julianDay
+ date
;
2617 Calendar::getDefaultMonthInYear()
2623 Calendar::getDefaultDayInMonth(int32_t /*month*/)
2629 int32_t Calendar::getLocalDOW()
2631 // Get zero-based localized DOW, valid range 0..6. This is the DOW
2632 // we are looking for.
2633 int32_t dowLocal
= 0;
2634 switch (resolveFields(kDOWPrecedence
)) {
2636 dowLocal
= internalGet(UCAL_DAY_OF_WEEK
) - fFirstDayOfWeek
;
2639 dowLocal
= internalGet(UCAL_DOW_LOCAL
) - 1;
2644 dowLocal
= dowLocal
% 7;
2651 int32_t Calendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy
, int32_t woy
)
2653 // We have UCAL_YEAR_WOY and UCAL_WEEK_OF_YEAR - from those, determine
2654 // what year we fall in, so that other code can set it properly.
2655 // (code borrowed from computeWeekFields and handleComputeJulianDay)
2658 // First, we need a reliable DOW.
2659 UCalendarDateFields bestField
= resolveFields(kDatePrecedence
); // !! Note: if subclasses have a different table, they should override handleGetExtendedYearFromWeekFields
2662 int32_t dowLocal
= getLocalDOW(); // 0..6
2663 int32_t firstDayOfWeek
= getFirstDayOfWeek(); // Localized fdw
2664 int32_t jan1Start
= handleComputeMonthStart(yearWoy
, 0, FALSE
);
2665 int32_t nextJan1Start
= handleComputeMonthStart(yearWoy
+1, 0, FALSE
); // next year's Jan1 start
2667 // At this point julianDay is the 0-based day BEFORE the first day of
2668 // January 1, year 1 of the given calendar. If julianDay == 0, it
2669 // specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
2670 // or Gregorian). (or it is before the month we are in, if useMonth is True)
2672 // At this point we need to process the WEEK_OF_MONTH or
2673 // WEEK_OF_YEAR, which are similar, or the DAY_OF_WEEK_IN_MONTH.
2674 // First, perform initial shared computations. These locate the
2675 // first week of the period.
2677 // Get the 0-based localized DOW of day one of the month or year.
2678 // Valid range 0..6.
2679 int32_t first
= julianDayToDayOfWeek(jan1Start
+ 1) - firstDayOfWeek
;
2683 int32_t nextFirst
= julianDayToDayOfWeek(nextJan1Start
+ 1) - firstDayOfWeek
;
2684 if (nextFirst
< 0) {
2688 int32_t minDays
= getMinimalDaysInFirstWeek();
2689 UBool jan1InPrevYear
= FALSE
; // January 1st in the year of WOY is the 1st week? (i.e. first week is < minimal )
2690 UBool nextJan1InPrevYear
= FALSE
; // January 1st of Year of WOY + 1 is in the first week?
2692 if((7 - first
) < minDays
) {
2693 jan1InPrevYear
= TRUE
;
2696 if((7 - nextFirst
) < minDays
) {
2697 nextJan1InPrevYear
= TRUE
;
2701 case UCAL_WEEK_OF_YEAR
:
2703 if(jan1InPrevYear
== TRUE
) {
2704 // the first week of January is in the previous year
2705 // therefore WOY1 is always solidly within yearWoy
2708 // First WOY is split between two years
2709 if( dowLocal
< first
) { // we are prior to Jan 1
2710 return yearWoy
-1; // previous year
2712 return yearWoy
; // in this year
2715 } else if(woy
>= getLeastMaximum(bestField
)) {
2716 // we _might_ be in the last week..
2717 int32_t jd
= // Calculate JD of our target day:
2718 jan1Start
+ // JD of Jan 1
2719 (7-first
) + // days in the first week (Jan 1.. )
2720 (woy
-1)*7 + // add the weeks of the year
2721 dowLocal
; // the local dow (0..6) of last week
2722 if(jan1InPrevYear
==FALSE
) {
2723 jd
-= 7; // woy already includes Jan 1's week.
2726 if( (jd
+1) >= nextJan1Start
) {
2727 // we are in week 52 or 53 etc. - actual year is yearWoy+1
2730 // still in yearWoy;
2734 // we're not possibly in the last week -must be ywoy
2740 if((internalGet(UCAL_MONTH
)==0) &&
2741 (woy
>= getLeastMaximum(UCAL_WEEK_OF_YEAR
))) {
2742 return yearWoy
+1; // month 0, late woy = in the next year
2744 //if(nextJan1InPrevYear) {
2745 if(internalGet(UCAL_MONTH
)==0) {
2753 //(internalGet(UCAL_DATE) <= (7-first)) /* && in minDow */ ) {
2754 //within 1st week and in this month..
2759 default: // assume the year is appropriate
2764 #if defined (U_DEBUG_CAL)
2765 fprintf(stderr
, "%s:%d - forgot a return on field %s\n", __FILE__
, __LINE__
, fldName(bestField
));
2771 int32_t Calendar::handleGetMonthLength(int32_t extendedYear
, int32_t month
) const
2773 return handleComputeMonthStart(extendedYear
, month
+1, TRUE
) -
2774 handleComputeMonthStart(extendedYear
, month
, TRUE
);
2777 int32_t Calendar::handleGetYearLength(int32_t eyear
) const {
2778 return handleComputeMonthStart(eyear
+1, 0, FALSE
) -
2779 handleComputeMonthStart(eyear
, 0, FALSE
);
2783 Calendar::getActualMaximum(UCalendarDateFields field
, UErrorCode
& status
) const
2789 if(U_FAILURE(status
)) return 0;
2790 Calendar
*cal
= clone();
2791 if(!cal
) { status
= U_MEMORY_ALLOCATION_ERROR
; return 0; }
2792 cal
->prepareGetActual(field
,FALSE
,status
);
2793 result
= handleGetMonthLength(cal
->get(UCAL_EXTENDED_YEAR
, status
), cal
->get(UCAL_MONTH
, status
));
2798 case UCAL_DAY_OF_YEAR
:
2800 if(U_FAILURE(status
)) return 0;
2801 Calendar
*cal
= clone();
2802 if(!cal
) { status
= U_MEMORY_ALLOCATION_ERROR
; return 0; }
2803 cal
->prepareGetActual(field
,FALSE
,status
);
2804 result
= handleGetYearLength(cal
->get(UCAL_EXTENDED_YEAR
, status
));
2819 case UCAL_JULIAN_DAY
:
2820 case UCAL_MILLISECONDS_IN_DAY
:
2821 // These fields all have fixed minima/maxima
2822 result
= getMaximum(field
);
2826 // For all other fields, do it the hard way....
2827 result
= getActualHelper(field
, getLeastMaximum(field
), getMaximum(field
),status
);
2835 * Prepare this calendar for computing the actual minimum or maximum.
2836 * This method modifies this calendar's fields; it is called on a
2837 * temporary calendar.
2839 * <p>Rationale: The semantics of getActualXxx() is to return the
2840 * maximum or minimum value that the given field can take, taking into
2841 * account other relevant fields. In general these other fields are
2842 * larger fields. For example, when computing the actual maximum
2843 * DATE, the current value of DATE itself is ignored,
2844 * as is the value of any field smaller.
2846 * <p>The time fields all have fixed minima and maxima, so we don't
2847 * need to worry about them. This also lets us set the
2848 * MILLISECONDS_IN_DAY to zero to erase any effects the time fields
2849 * might have when computing date fields.
2851 * <p>DAY_OF_WEEK is adjusted specially for the WEEK_OF_MONTH and
2852 * WEEK_OF_YEAR fields to ensure that they are computed correctly.
2855 void Calendar::prepareGetActual(UCalendarDateFields field
, UBool isMinimum
, UErrorCode
&status
)
2857 set(UCAL_MILLISECONDS_IN_DAY
, 0);
2862 case UCAL_EXTENDED_YEAR
:
2863 set(UCAL_DAY_OF_YEAR
, getGreatestMinimum(UCAL_DAY_OF_YEAR
));
2867 set(UCAL_DATE
, getGreatestMinimum(UCAL_DATE
));
2870 case UCAL_DAY_OF_WEEK_IN_MONTH
:
2871 // For dowim, the maximum occurs for the DOW of the first of the
2874 set(UCAL_DAY_OF_WEEK
, get(UCAL_DAY_OF_WEEK
, status
)); // Make this user set
2877 case UCAL_WEEK_OF_MONTH
:
2878 case UCAL_WEEK_OF_YEAR
:
2879 // If we're counting weeks, set the day of the week to either the
2880 // first or last localized DOW. We know the last week of a month
2881 // or year will contain the first day of the week, and that the
2882 // first week will contain the last DOW.
2884 int32_t dow
= fFirstDayOfWeek
;
2886 dow
= (dow
+ 6) % 7; // set to last DOW
2887 if (dow
< UCAL_SUNDAY
) {
2891 #if defined (U_DEBUG_CAL)
2892 fprintf(stderr
, "prepareGetActualHelper(WOM/WOY) - dow=%d\n", dow
);
2894 set(UCAL_DAY_OF_WEEK
, dow
);
2901 // Do this last to give it the newest time stamp
2902 set(field
, getGreatestMinimum(field
));
2905 int32_t Calendar::getActualHelper(UCalendarDateFields field
, int32_t startValue
, int32_t endValue
, UErrorCode
&status
) const
2907 #if defined (U_DEBUG_CAL)
2908 fprintf(stderr
, "getActualHelper(%d,%d .. %d, %s)\n", field
, startValue
, endValue
, u_errorName(status
));
2910 if (startValue
== endValue
) {
2911 // if we know that the maximum value is always the same, just return it
2915 int32_t delta
= (endValue
> startValue
) ? 1 : -1;
2917 // clone the calendar so we don't mess with the real one, and set it to
2918 // accept anything for the field values
2919 if(U_FAILURE(status
)) return startValue
;
2920 Calendar
*work
= clone();
2921 if(!work
) { status
= U_MEMORY_ALLOCATION_ERROR
; return startValue
; }
2922 work
->setLenient(TRUE
);
2923 #if defined (U_DEBUG_CAL)
2924 fprintf(stderr
, "%s:%d - getActualHelper - %s\n", __FILE__
, __LINE__
, u_errorName(status
));
2926 work
->prepareGetActual(field
, delta
< 0, status
);
2927 #if defined (U_DEBUG_CAL)
2928 fprintf(stderr
, "%s:%d - getActualHelper - %s\n", __FILE__
, __LINE__
, u_errorName(status
));
2931 // now try each value from the start to the end one by one until
2932 // we get a value that normalizes to another value. The last value that
2933 // normalizes to itself is the actual maximum for the current date
2934 int32_t result
= startValue
;
2936 #if defined (U_DEBUG_CAL)
2937 fprintf(stderr
, "%s:%d - getActualHelper - %s\n", __FILE__
, __LINE__
, u_errorName(status
));
2939 work
->set(field
, startValue
);
2940 #if defined (U_DEBUG_CAL)
2941 fprintf(stderr
, "%s:%d - getActualHelper - %s (set to %d)\n", __FILE__
, __LINE__
, u_errorName(status
), startValue
);
2943 if (work
->get(field
, status
) != startValue
) {
2944 #if defined (U_DEBUG_CAL)
2945 fprintf(stderr
, "getActualHelper(fld %d) - got %d (not %d), BREAK - %s\n", field
, work
->get(field
,status
), startValue
, u_errorName(status
));
2949 result
= startValue
;
2950 startValue
+= delta
;
2951 #if defined (U_DEBUG_CAL)
2952 fprintf(stderr
, "getActualHelper(%d) result=%d (start), start += %d to %d\n", field
, result
, delta
, startValue
);
2955 } while (result
!= endValue
&& U_SUCCESS(status
));
2957 #if defined (U_DEBUG_CAL)
2958 fprintf(stderr
, "getActualHelper(%d) = %d\n", field
, result
);
2966 // -------------------------------------
2969 Calendar::setWeekCountData(const Locale
& desiredLocale
, const char *type
, UErrorCode
& status
)
2971 // Read the week count data from the resource bundle. This should
2974 // DateTimeElements:intvector {
2975 // 1, // first day of week
2976 // 1 // min days in week
2978 // Both have a range of 1..7
2981 if (U_FAILURE(status
)) return;
2983 fFirstDayOfWeek
= UCAL_SUNDAY
;
2984 fMinimalDaysInFirstWeek
= 1;
2986 CalendarData
calData(desiredLocale
, type
, status
);
2987 // If the resource data doesn't seem to be present at all, then use last-resort
2989 UResourceBundle
*dateTimeElements
= calData
.getByKey(kDateTimeElements
, status
);
2991 if (U_FAILURE(status
))
2993 #if defined (U_DEBUG_CALDATA)
2994 fprintf(stderr
, " Failure loading dateTimeElements = %s\n", u_errorName(status
));
2996 status
= U_USING_FALLBACK_WARNING
;
3000 U_LOCALE_BASED(locBased
, *this);
3001 locBased
.setLocaleIDs(ures_getLocaleByType(dateTimeElements
, ULOC_VALID_LOCALE
, &status
),
3002 ures_getLocaleByType(dateTimeElements
, ULOC_ACTUAL_LOCALE
, &status
));
3003 if (U_SUCCESS(status
)) {
3004 #if defined (U_DEBUG_CAL)
3005 fprintf(stderr
, " Valid=%s, Actual=%s\n", validLocale
, actualLocale
);
3008 const int32_t *dateTimeElementsArr
= ures_getIntVector(dateTimeElements
, &arrLen
, &status
);
3010 if(U_SUCCESS(status
) && arrLen
== 2
3011 && 1 <= dateTimeElementsArr
[0] && dateTimeElementsArr
[0] <= 7
3012 && 1 <= dateTimeElementsArr
[1] && dateTimeElementsArr
[1] <= 7)
3014 fFirstDayOfWeek
= (UCalendarDaysOfWeek
)dateTimeElementsArr
[0];
3015 fMinimalDaysInFirstWeek
= (uint8_t)dateTimeElementsArr
[1];
3018 status
= U_INVALID_FORMAT_ERROR
;
3022 // do NOT close dateTimeElements
3026 * Recompute the time and update the status fields isTimeSet
3027 * and areFieldsSet. Callers should check isTimeSet and only
3028 * call this method if isTimeSet is false.
3031 Calendar::updateTime(UErrorCode
& status
)
3033 computeTime(status
);
3034 if(U_FAILURE(status
))
3037 // If we are lenient, we need to recompute the fields to normalize
3038 // the values. Also, if we haven't set all the fields yet (i.e.,
3039 // in a newly-created object), we need to fill in the fields. [LIU]
3040 if (isLenient() || ! fAreAllFieldsSet
)
3041 fAreFieldsSet
= FALSE
;
3044 fAreFieldsVirtuallySet
= FALSE
;
3048 Calendar::getLocale(ULocDataLocaleType type
, UErrorCode
& status
) const {
3049 U_LOCALE_BASED(locBased
, *this);
3050 return locBased
.getLocale(type
, status
);
3054 Calendar::getLocaleID(ULocDataLocaleType type
, UErrorCode
& status
) const {
3055 U_LOCALE_BASED(locBased
, *this);
3056 return locBased
.getLocaleID(type
, status
);
3061 #endif /* #if !UCONFIG_NO_FORMATTING */