2 *******************************************************************************
3 * Copyright (C) 1997-2009, International Business Machines Corporation and *
4 * others. All Rights Reserved. *
5 *******************************************************************************
9 * Modification History:
11 * Date Name Description
12 * 12/05/96 clhuang Creation.
13 * 04/21/97 aliu General clean-up and bug fixing.
14 * 05/08/97 aliu Fixed Hashtable code per code review.
15 * 07/09/97 helena Changed createInstance to createDefault.
16 * 07/29/97 aliu Updated with all-new list of 96 UNIX-derived
17 * TimeZones. Changed mechanism to load from static
18 * array rather than resource bundle.
19 * 07/07/1998 srl Bugfixes from the Java side: UTC GMT CAT NST
20 * Added getDisplayName API
21 * going to add custom parsing.
24 * - should getDisplayName cache something?
25 * - should custom time zones be cached? [probably]
26 * 08/10/98 stephen Brought getDisplayName() API in-line w/ conventions
27 * 08/19/98 stephen Changed createTimeZone() to never return 0
28 * 09/02/98 stephen Added getOffset(monthLen) and hasSameRules()
29 * 09/15/98 stephen Added getStaticClassID()
30 * 02/22/99 stephen Removed character literals for EBCDIC safety
31 * 05/04/99 stephen Changed initDefault() for Mutex issues
32 * 07/12/99 helena HPUX 11 CC Port.
33 * 12/03/99 aliu Moved data out of static table into icudata.dll.
34 * Substantial rewrite of zone lookup, default zone, and
35 * available IDs code. Misc. cleanup.
36 *********************************************************************************/
38 #include "unicode/utypes.h"
39 #include "unicode/ustring.h"
43 # include "uresimp.h" // for debugging
45 static void debug_tz_loc(const char *f
, int32_t l
)
47 fprintf(stderr
, "%s:%d: ", f
, l
);
50 static void debug_tz_msg(const char *pat
, ...)
54 vfprintf(stderr
, pat
, ap
);
57 static char gStrBuf
[256];
58 #define U_DEBUG_TZ_STR(x) u_austrncpy(gStrBuf,x,sizeof(gStrBuf)-1)
59 // must use double parens, i.e.: U_DEBUG_TZ_MSG(("four is: %d",4));
60 #define U_DEBUG_TZ_MSG(x) {debug_tz_loc(__FILE__,__LINE__);debug_tz_msg x;}
62 #define U_DEBUG_TZ_MSG(x)
65 #if !UCONFIG_NO_FORMATTING
67 #include "unicode/simpletz.h"
68 #include "unicode/smpdtfmt.h"
69 #include "unicode/calendar.h"
70 #include "unicode/gregocal.h"
71 #include "unicode/ures.h"
73 #include "uresimp.h" // struct UResourceBundle
76 #include "unicode/udata.h"
80 #include "unicode/strenum.h"
84 #define kZONEINFO "zoneinfo"
85 #define kREGIONS "Regions"
86 #define kZONES "Zones"
87 #define kRULES "Rules"
88 #define kNAMES "Names"
89 #define kDEFAULT "Default"
90 #define kMAX_CUSTOM_HOUR 23
91 #define kMAX_CUSTOM_MIN 59
92 #define kMAX_CUSTOM_SEC 59
95 #define ZERO_DIGIT 0x0030
97 // Static data and constants
99 static const UChar GMT_ID
[] = {0x47, 0x4D, 0x54, 0x00}; /* "GMT" */
100 static const UChar Z_STR
[] = {0x7A, 0x00}; /* "z" */
101 static const UChar ZZZZ_STR
[] = {0x7A, 0x7A, 0x7A, 0x7A, 0x00}; /* "zzzz" */
102 static const int32_t GMT_ID_LENGTH
= 3;
105 static UMTX TZSET_LOCK
;
106 static U_NAMESPACE_QUALIFIER TimeZone
* DEFAULT_ZONE
= NULL
;
107 static U_NAMESPACE_QUALIFIER TimeZone
* _GMT
= NULL
; // cf. TimeZone::GMT
109 static char TZDATA_VERSION
[16];
111 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
112 static U_NAMESPACE_QUALIFIER UnicodeString
* OLSON_IDS
= 0;
116 static UBool U_CALLCONV
timeZone_cleanup(void)
118 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
129 uprv_memset(TZDATA_VERSION
, 0, sizeof(TZDATA_VERSION
));
136 umtx_destroy(&TZSET_LOCK
);
147 * The Olson data is stored the "zoneinfo" resource bundle.
148 * Sub-resources are organized into three ranges of data: Zones, final
149 * rules, and country tables. There is also a meta-data resource
150 * which has 3 integers: The number of zones, rules, and countries,
151 * respectively. The country count includes the non-country 'Default'.
153 static int32_t OLSON_ZONE_COUNT
= 0; // count of zones
156 * Given a pointer to an open "zoneinfo" resource, load up the Olson
157 * meta-data. Return TRUE if successful.
159 static UBool
getOlsonMeta(const UResourceBundle
* top
) {
160 if (OLSON_ZONE_COUNT
== 0) {
161 UErrorCode ec
= U_ZERO_ERROR
;
163 ures_initStackObject(&res
);
164 ures_getByKey(top
, kZONES
, &res
, &ec
);
166 OLSON_ZONE_COUNT
= ures_getSize(&res
);
167 U_DEBUG_TZ_MSG(("OZC%d\n",OLSON_ZONE_COUNT
));
171 return (OLSON_ZONE_COUNT
> 0);
175 * Load up the Olson meta-data. Return TRUE if successful.
177 static UBool
getOlsonMeta() {
178 if (OLSON_ZONE_COUNT
== 0) {
179 UErrorCode ec
= U_ZERO_ERROR
;
180 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
186 return (OLSON_ZONE_COUNT
> 0);
189 static int32_t findInStringArray(UResourceBundle
* array
, const UnicodeString
& id
, UErrorCode
&status
)
196 int32_t limit
= ures_getSize(array
);
198 int32_t lastMid
= INT32_MAX
;
199 if(U_FAILURE(status
) || (limit
< 1)) {
202 U_DEBUG_TZ_MSG(("fisa: Looking for %s, between %d and %d\n", U_DEBUG_TZ_STR(UnicodeString(id
).getTerminatedBuffer()), start
, limit
));
205 mid
= (int32_t)((start
+ limit
) / 2);
206 if (lastMid
== mid
) { /* Have we moved? */
207 break; /* We haven't moved, and it wasn't found. */
210 u
= ures_getStringByIndex(array
, mid
, &len
, &status
);
211 if (U_FAILURE(status
)) {
214 U_DEBUG_TZ_MSG(("tz: compare to %s, %d .. [%d] .. %d\n", U_DEBUG_TZ_STR(u
), start
, mid
, limit
));
215 copy
.setTo(TRUE
, u
, len
);
216 int r
= id
.compare(copy
);
218 U_DEBUG_TZ_MSG(("fisa: found at %d\n", mid
));
226 U_DEBUG_TZ_MSG(("fisa: not found\n"));
231 * Fetch a specific zone by name. Replaces the getByKey call.
232 * @param top Top timezone resource
233 * @param id Time zone ID
234 * @param oldbundle Bundle for reuse (or NULL). see 'ures_open()'
235 * @return the zone's bundle if found, or undefined if error. Reuses oldbundle.
237 static UResourceBundle
* getZoneByName(const UResourceBundle
* top
, const UnicodeString
& id
, UResourceBundle
*oldbundle
, UErrorCode
& status
) {
238 // load the Rules object
239 UResourceBundle
*tmp
= ures_getByKey(top
, kNAMES
, NULL
, &status
);
241 // search for the string
242 int32_t idx
= findInStringArray(tmp
, id
, status
);
244 if((idx
== -1) && U_SUCCESS(status
)) {
246 status
= U_MISSING_RESOURCE_ERROR
;
247 //ures_close(oldbundle);
250 U_DEBUG_TZ_MSG(("gzbn: oldbundle= size %d, type %d, %s\n", ures_getSize(tmp
), ures_getType(tmp
), u_errorName(status
)));
251 tmp
= ures_getByKey(top
, kZONES
, tmp
, &status
); // get Zones object from top
252 U_DEBUG_TZ_MSG(("gzbn: loaded ZONES, size %d, type %d, path %s %s\n", ures_getSize(tmp
), ures_getType(tmp
), ures_getPath(tmp
), u_errorName(status
)));
253 oldbundle
= ures_getByIndex(tmp
, idx
, oldbundle
, &status
); // get nth Zone object
254 U_DEBUG_TZ_MSG(("gzbn: loaded z#%d, size %d, type %d, path %s, %s\n", idx
, ures_getSize(oldbundle
), ures_getType(oldbundle
), ures_getPath(oldbundle
), u_errorName(status
)));
257 if(U_FAILURE(status
)) {
258 //ures_close(oldbundle);
266 UResourceBundle
* TimeZone::loadRule(const UResourceBundle
* top
, const UnicodeString
& ruleid
, UResourceBundle
* oldbundle
, UErrorCode
& status
) {
268 ruleid
.extract(0, sizeof(key
)-1, key
, (int32_t)sizeof(key
)-1, US_INV
);
269 U_DEBUG_TZ_MSG(("loadRule(%s)\n", key
));
270 UResourceBundle
*r
= ures_getByKey(top
, kRULES
, oldbundle
, &status
);
271 U_DEBUG_TZ_MSG(("loadRule(%s) -> kRULES [%s]\n", key
, u_errorName(status
)));
272 r
= ures_getByKey(r
, key
, r
, &status
);
273 U_DEBUG_TZ_MSG(("loadRule(%s) -> item [%s]\n", key
, u_errorName(status
)));
278 * Given an ID, open the appropriate resource for the given time zone.
279 * Dereference aliases if necessary.
281 * @param res resource, which must be ready for use (initialized but not open)
282 * @param ec input-output error code
283 * @return top-level resource bundle
285 static UResourceBundle
* openOlsonResource(const UnicodeString
& id
,
286 UResourceBundle
& res
,
291 id
.extract(0, sizeof(buf
)-1, buf
, sizeof(buf
), "");
293 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
294 U_DEBUG_TZ_MSG(("pre: res sz=%d\n", ures_getSize(&res
)));
295 /* &res = */ getZoneByName(top
, id
, &res
, ec
);
296 // Dereference if this is an alias. Docs say result should be 1
297 // but it is 0 in 2.8 (?).
298 U_DEBUG_TZ_MSG(("Loading zone '%s' (%s, size %d) - %s\n", buf
, ures_getKey((UResourceBundle
*)&res
), ures_getSize(&res
), u_errorName(ec
)));
299 if (ures_getSize(&res
) <= 1 && getOlsonMeta(top
)) {
300 int32_t deref
= ures_getInt(&res
, &ec
) + 0;
301 U_DEBUG_TZ_MSG(("getInt: %s - type is %d\n", u_errorName(ec
), ures_getType(&res
)));
302 UResourceBundle
*ares
= ures_getByKey(top
, kZONES
, NULL
, &ec
); // dereference Zones section
303 ures_getByIndex(ares
, deref
, &res
, &ec
);
305 U_DEBUG_TZ_MSG(("alias to #%d (%s) - %s\n", deref
, "??", u_errorName(ec
)));
307 U_DEBUG_TZ_MSG(("not an alias - size %d\n", ures_getSize(&res
)));
309 U_DEBUG_TZ_MSG(("%s - final status is %s\n", buf
, u_errorName(ec
)));
313 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
316 * Load all the ids from the "zoneinfo" resource bundle into a static
317 * array that we hang onto. This is _only_ used to implement the
318 * deprecated createAvailableIDs() API.
320 static UBool
loadOlsonIDs() {
321 if (OLSON_IDS
!= 0) {
325 UErrorCode ec
= U_ZERO_ERROR
;
326 UnicodeString
* ids
= 0;
328 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
329 UResourceBundle
*nres
= ures_getByKey(top
, kNAMES
, NULL
, &ec
); // dereference Names section
333 count
= ures_getSize(nres
);
334 ids
= new UnicodeString
[(count
> 0) ? count
: 1];
335 // Null pointer check
337 for (int32_t i
=0; i
<count
; ++i
) {
339 const UChar
* id
= ures_getStringByIndex(nres
, i
, &idLen
, &ec
);
340 ids
[i
].fastCopyFrom(UnicodeString(TRUE
, id
, idLen
));
346 ec
= U_MEMORY_ALLOCATION_ERROR
;
357 // Keep mutexed operations as short as possible by doing all
358 // computations first, then doing pointer copies within the mutex.
360 if (OLSON_IDS
== 0) {
363 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
367 // If another thread initialized the statics first, then delete
375 // -------------------------------------
377 const TimeZone
* U_EXPORT2
378 TimeZone::getGMT(void)
381 UMTX_CHECK(&LOCK
, (_GMT
== NULL
), needsInit
); /* This is here to prevent race conditions. */
383 // Initialize _GMT independently of other static data; it should
384 // be valid even if we can't load the time zone UDataMemory.
388 _GMT
= new SimpleTimeZone(0, UnicodeString(TRUE
, GMT_ID
, GMT_ID_LENGTH
));
389 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
396 // *****************************************************************************
398 // *****************************************************************************
400 UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(TimeZone
)
407 // -------------------------------------
409 TimeZone::TimeZone(const UnicodeString
&id
)
414 // -------------------------------------
416 TimeZone::~TimeZone()
420 // -------------------------------------
422 TimeZone::TimeZone(const TimeZone
&source
)
423 : UObject(source
), fID(source
.fID
)
427 // -------------------------------------
430 TimeZone::operator=(const TimeZone
&right
)
432 if (this != &right
) fID
= right
.fID
;
436 // -------------------------------------
439 TimeZone::operator==(const TimeZone
& that
) const
441 return getDynamicClassID() == that
.getDynamicClassID() &&
445 // -------------------------------------
448 TimeZone::createTimeZone(const UnicodeString
& ID
)
450 /* We first try to lookup the zone ID in our system list. If this
451 * fails, we try to parse it as a custom string GMT[+-]hh:mm. If
452 * all else fails, we return GMT, which is probably not what the
453 * user wants, but at least is a functioning TimeZone object.
455 * We cannot return NULL, because that would break compatibility
458 TimeZone
* result
= createSystemTimeZone(ID
);
461 U_DEBUG_TZ_MSG(("failed to load system time zone with id - falling to custom"));
462 result
= createCustomTimeZone(ID
);
465 U_DEBUG_TZ_MSG(("failed to load time zone with id - falling to GMT"));
466 const TimeZone
* temptz
= getGMT();
467 if (temptz
== NULL
) {
470 result
= temptz
->clone();
477 * Lookup the given name in our system zone table. If found,
478 * instantiate a new zone of that name and return it. If not
482 TimeZone::createSystemTimeZone(const UnicodeString
& id
) {
484 UErrorCode ec
= U_ZERO_ERROR
;
486 ures_initStackObject(&res
);
487 U_DEBUG_TZ_MSG(("pre-err=%s\n", u_errorName(ec
)));
488 UResourceBundle
*top
= openOlsonResource(id
, res
, ec
);
489 U_DEBUG_TZ_MSG(("post-err=%s\n", u_errorName(ec
)));
491 z
= new OlsonTimeZone(top
, &res
, ec
);
495 U_DEBUG_TZ_MSG(("cstz: olson time zone failed to initialize - err %s\n", u_errorName(ec
)));
501 U_DEBUG_TZ_MSG(("cstz: failed to create, err %s\n", u_errorName(ec
)));
508 // -------------------------------------
511 * Initialize DEFAULT_ZONE from the system default time zone. The
512 * caller should confirm that DEFAULT_ZONE is NULL before calling.
513 * Upon return, DEFAULT_ZONE will not be NULL, unless operator new()
516 * Must be called OUTSIDE mutex.
519 TimeZone::initDefault()
521 // We access system timezone data through TPlatformUtilities,
522 // including tzset(), timezone, and tzname[].
523 int32_t rawOffset
= 0;
526 // First, try to create a system timezone, based
527 // on the string ID in tzname[0].
529 // NOTE: Local mutex here. TimeZone mutex below
530 // mutexed to avoid threading issues in the platform functions.
531 // Some of the locale/timezone OS functions may not be thread safe,
532 // so the intent is that any setting from anywhere within ICU
533 // happens while the ICU mutex is held.
534 // The operating system might actually use ICU to implement timezones.
535 // So we may have ICU calling ICU here, like on AIX.
536 // In order to prevent a double lock of a non-reentrant mutex in a
537 // different part of ICU, we use TZSET_LOCK to allow only one instance
538 // of ICU to query these thread unsafe OS functions at any given time.
539 Mutex
lock(&TZSET_LOCK
);
541 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
542 uprv_tzset(); // Initialize tz... system data
544 // Get the timezone ID from the host. This function should do
545 // any required host-specific remapping; e.g., on Windows this
546 // function maps the Date and Time control panel setting to an
548 hostID
= uprv_tzname(0);
550 // Invert sign because UNIX semantics are backwards
551 rawOffset
= uprv_timezone() * -U_MILLIS_PER_SECOND
;
555 UMTX_CHECK(&LOCK
, (DEFAULT_ZONE
!= NULL
), initialized
);
557 /* Hrmph? Either a race condition happened, or tzset initialized ICU. */
561 TimeZone
* default_zone
= NULL
;
563 /* Make sure that the string is NULL terminated to prevent BoundsChecker/Purify warnings. */
564 UnicodeString
hostStrID(hostID
, -1, US_INV
);
565 hostStrID
.append((UChar
)0);
566 hostStrID
.truncate(hostStrID
.length()-1);
567 default_zone
= createSystemTimeZone(hostStrID
);
569 int32_t hostIDLen
= hostStrID
.length();
570 if (default_zone
!= NULL
&& rawOffset
!= default_zone
->getRawOffset()
571 && (3 <= hostIDLen
&& hostIDLen
<= 4))
573 // Uh oh. This probably wasn't a good id.
574 // It was probably an ambiguous abbreviation
580 // NOTE: As of ICU 2.8, we no longer have an offsets table, since
581 // historical zones can change offset over time. If we add
582 // build-time heuristics to infer the "most frequent" raw offset
583 // of a zone, we can build tables and institute defaults, as done
586 // If we couldn't get the time zone ID from the host, use
587 // the default host timezone offset. Further refinements
588 // to this include querying the host to determine if DST
589 // is in use or not and possibly using the host locale to
590 // select from multiple zones at a the same offset. We
591 // don't do any of this now, but we could easily add this.
592 if (default_zone
== NULL
) {
593 // Use the designated default in the time zone list that has the
594 // appropriate GMT offset, if there is one.
596 const OffsetIndex
* index
= INDEX_BY_OFFSET
;
599 if (index
->gmtOffset
> rawOffset
) {
600 // Went past our desired offset; no match found
603 if (index
->gmtOffset
== rawOffset
) {
604 // Found our desired offset
605 default_zone
= createSystemTimeZone(ZONE_IDS
[index
->defaultZone
]);
608 // Compute the position of the next entry. If the delta value
609 // in this entry is zero, then there is no next entry.
610 uint16_t delta
= index
->nextEntryDelta
;
614 index
= (const OffsetIndex
*)((int8_t*)index
+ delta
);
619 // Construct a fixed standard zone with the host's ID
621 if (default_zone
== NULL
) {
622 default_zone
= new SimpleTimeZone(rawOffset
, hostStrID
);
625 // If we _still_ don't have a time zone, use GMT.
626 if (default_zone
== NULL
) {
627 const TimeZone
* temptz
= getGMT();
628 // If we can't use GMT, get out.
629 if (temptz
== NULL
) {
632 default_zone
= temptz
->clone();
635 // If DEFAULT_ZONE is still NULL, set it up.
637 if (DEFAULT_ZONE
== NULL
) {
638 DEFAULT_ZONE
= default_zone
;
640 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
647 // -------------------------------------
650 TimeZone::createDefault()
652 /* This is here to prevent race conditions. */
654 UMTX_CHECK(&LOCK
, (DEFAULT_ZONE
== NULL
), needsInit
);
659 Mutex
lock(&LOCK
); // In case adoptDefault is called
660 return (DEFAULT_ZONE
!= NULL
) ? DEFAULT_ZONE
->clone() : NULL
;
663 // -------------------------------------
666 TimeZone::adoptDefault(TimeZone
* zone
)
670 TimeZone
* old
= NULL
;
672 umtx_init(&LOCK
); /* This is here to prevent race conditions. */
679 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
682 // -------------------------------------
685 TimeZone::setDefault(const TimeZone
& zone
)
687 adoptDefault(zone
.clone());
690 //----------------------------------------------------------------------
693 * This is the default implementation for subclasses that do not
694 * override this method. This implementation calls through to the
695 * 8-argument getOffset() method after suitable computations, and
696 * correctly adjusts GMT millis to local millis when necessary.
698 void TimeZone::getOffset(UDate date
, UBool local
, int32_t& rawOffset
,
699 int32_t& dstOffset
, UErrorCode
& ec
) const {
704 rawOffset
= getRawOffset();
706 date
+= rawOffset
; // now in local standard millis
709 // When local == TRUE, date might not be in local standard
710 // millis. getOffset taking 7 parameters used here assume
711 // the given time in day is local standard time.
712 // At STD->DST transition, there is a range of time which
713 // does not exist. When 'date' is in this time range
714 // (and local == TRUE), this method interprets the specified
715 // local time as DST. At DST->STD transition, there is a
716 // range of time which occurs twice. In this case, this
717 // method interprets the specified local time as STD.
718 // To support the behavior above, we need to call getOffset
719 // (with 7 args) twice when local == true and DST is
720 // detected in the initial call.
721 for (int32_t pass
=0; ; ++pass
) {
722 int32_t year
, month
, dom
, dow
;
723 double day
= uprv_floor(date
/ U_MILLIS_PER_DAY
);
724 int32_t millis
= (int32_t) (date
- day
* U_MILLIS_PER_DAY
);
726 Grego::dayToFields(day
, year
, month
, dom
, dow
);
728 dstOffset
= getOffset(GregorianCalendar::AD
, year
, month
, dom
,
729 (uint8_t) dow
, millis
,
730 Grego::monthLength(year
, month
),
733 // Recompute if local==TRUE, dstOffset!=0.
734 if (pass
!=0 || !local
|| dstOffset
== 0) {
737 // adjust to local standard millis
742 // -------------------------------------
744 // New available IDs API as of ICU 2.4. Uses StringEnumeration API.
746 class TZEnumeration
: public StringEnumeration
{
749 // Map into to zones. Our results are zone[map[i]] for
750 // i=0..len-1, where zone[i] is the i-th Olson zone. If map==NULL
751 // then our results are zone[i] for i=0..len-1. Len will be zero
752 // iff the zone data could not be loaded.
757 UBool
getID(int32_t i
) {
758 UErrorCode ec
= U_ZERO_ERROR
;
760 const UChar
* id
= NULL
;
761 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
762 top
= ures_getByKey(top
, kNAMES
, top
, &ec
); // dereference Zones section
763 id
= ures_getStringByIndex(top
, i
, &idLen
, &ec
);
768 unistr
.fastCopyFrom(UnicodeString(TRUE
, id
, idLen
));
771 return U_SUCCESS(ec
);
775 TZEnumeration() : map(NULL
), len(0), pos(0) {
776 if (getOlsonMeta()) {
777 len
= OLSON_ZONE_COUNT
;
781 TZEnumeration(int32_t rawOffset
) : map(NULL
), len(0), pos(0) {
782 if (!getOlsonMeta()) {
786 // Allocate more space than we'll need. The end of the array will
788 map
= (int32_t*)uprv_malloc(OLSON_ZONE_COUNT
* sizeof(int32_t));
793 uprv_memset(map
, 0, sizeof(int32_t) * OLSON_ZONE_COUNT
);
796 for (int32_t i
=0; i
<OLSON_ZONE_COUNT
; ++i
) {
798 // This is VERY inefficient.
799 TimeZone
* z
= TimeZone::createTimeZone(unistr
);
800 // Make sure we get back the ID we wanted (if the ID is
801 // invalid we get back GMT).
802 if (z
!= 0 && z
->getID(s
) == unistr
&&
803 z
->getRawOffset() == rawOffset
) {
811 TZEnumeration(const char* country
) : map(NULL
), len(0), pos(0) {
812 if (!getOlsonMeta()) {
816 char key
[] = {0, 0, 0, 0,0, 0, 0,0, 0, 0,0}; // e.g., "US", or "Default" for no country
818 uprv_strncat(key
, country
, 2);
820 uprv_strcpy(key
, kDEFAULT
);
823 UErrorCode ec
= U_ZERO_ERROR
;
824 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
825 top
= ures_getByKey(top
, kREGIONS
, top
, &ec
); // dereference 'Regions' section
828 ures_initStackObject(&res
);
829 ures_getByKey(top
, key
, &res
, &ec
);
830 // The list of zones is a list of integers, from 0..n-1,
831 // where n is the total number of system zones.
832 const int32_t* v
= ures_getIntVector(&res
, &len
, &ec
);
835 map
= (int32_t*)uprv_malloc(sizeof(int32_t) * len
);
837 for (uint16_t i
=0; i
<len
; ++i
) {
838 U_ASSERT(v
[i
] >= 0 && v
[i
] < OLSON_ZONE_COUNT
);
843 U_DEBUG_TZ_MSG(("Failed to load tz for region %s: %s\n", country
, u_errorName(ec
)));
850 TZEnumeration(const TZEnumeration
&other
) : StringEnumeration(), map(NULL
), len(0), pos(0) {
852 if(other
.map
!= NULL
) {
853 map
= (int32_t *)uprv_malloc(other
.len
* sizeof(int32_t));
856 uprv_memcpy(map
, other
.map
, len
* sizeof(int32_t));
866 virtual ~TZEnumeration() {
870 virtual StringEnumeration
*clone() const {
871 return new TZEnumeration(*this);
874 virtual int32_t count(UErrorCode
& status
) const {
875 return U_FAILURE(status
) ? 0 : len
;
878 virtual const UnicodeString
* snext(UErrorCode
& status
) {
879 if (U_SUCCESS(status
) && pos
< len
) {
880 getID((map
== 0) ? pos
: map
[pos
]);
887 virtual void reset(UErrorCode
& /*status*/) {
892 static UClassID U_EXPORT2
getStaticClassID(void);
893 virtual UClassID
getDynamicClassID(void) const;
896 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TZEnumeration
)
898 StringEnumeration
* U_EXPORT2
899 TimeZone::createEnumeration() {
900 return new TZEnumeration();
903 StringEnumeration
* U_EXPORT2
904 TimeZone::createEnumeration(int32_t rawOffset
) {
905 return new TZEnumeration(rawOffset
);
908 StringEnumeration
* U_EXPORT2
909 TimeZone::createEnumeration(const char* country
) {
910 return new TZEnumeration(country
);
913 // -------------------------------------
915 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
917 const UnicodeString
**
918 TimeZone::createAvailableIDs(int32_t rawOffset
, int32_t& numIDs
)
920 // We are creating a new array to existing UnicodeString pointers.
921 // The caller will delete the array when done, but not the pointers
925 if (!loadOlsonIDs()) {
929 // Allocate more space than we'll need. The end of the array will
931 const UnicodeString
** ids
=
932 (const UnicodeString
** )uprv_malloc(OLSON_ZONE_COUNT
* sizeof(UnicodeString
*));
937 uprv_memset(ids
, 0, sizeof(UnicodeString
*) * OLSON_ZONE_COUNT
);
940 for (int32_t i
=0; i
<OLSON_ZONE_COUNT
; ++i
) {
941 // This is VERY inefficient.
942 TimeZone
* z
= TimeZone::createTimeZone(OLSON_IDS
[i
]);
943 // Make sure we get back the ID we wanted (if the ID is
944 // invalid we get back GMT).
945 if (z
!= 0 && z
->getID(s
) == OLSON_IDS
[i
] &&
946 z
->getRawOffset() == rawOffset
) {
947 ids
[numIDs
++] = &OLSON_IDS
[i
]; // [sic]
955 // -------------------------------------
957 const UnicodeString
**
958 TimeZone::createAvailableIDs(const char* country
, int32_t& numIDs
) {
960 // We are creating a new array to existing UnicodeString pointers.
961 // The caller will delete the array when done, but not the pointers
965 if (!loadOlsonIDs()) {
969 char key
[] = { 0, 0, 0,0, 0, 0,0, 0, 0 }; // e.g., "US", or "Default" for non-country zones
971 uprv_strncat(key
, country
, 2);
973 uprv_strcpy(key
, kDEFAULT
);
976 const UnicodeString
** ids
= 0;
978 UErrorCode ec
= U_ZERO_ERROR
;
979 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
980 UResourceBundle
*ares
= ures_getByKey(top
, kREGIONS
, NULL
, &ec
); // dereference Regions section
984 ures_initStackObject(&res
);
985 ures_getByKey(ares
, key
, &res
, &ec
);
986 U_DEBUG_TZ_MSG(("caI: on %s, err %s\n", country
, u_errorName(ec
)));
988 /* The list of zones is a list of integers, from 0..n-1,
989 * where n is the total number of system zones. The
990 * numbering corresponds exactly to the ordering of
993 const int32_t* v
= ures_getIntVector(&res
, &numIDs
, &ec
);
994 ids
= (const UnicodeString
**)
995 uprv_malloc(numIDs
* sizeof(UnicodeString
*));
999 for (int32_t i
=0; i
<numIDs
; ++i
) {
1000 ids
[i
] = &OLSON_IDS
[v
[i
]]; // [sic]
1012 // -------------------------------------
1014 const UnicodeString
**
1015 TimeZone::createAvailableIDs(int32_t& numIDs
)
1017 // We are creating a new array to existing UnicodeString pointers.
1018 // The caller will delete the array when done, but not the pointers
1021 if (!loadOlsonIDs()) {
1025 const UnicodeString
** ids
=
1026 (const UnicodeString
** )uprv_malloc(OLSON_ZONE_COUNT
* sizeof(UnicodeString
*));
1028 numIDs
= OLSON_ZONE_COUNT
;
1029 for (int32_t i
=0; i
<numIDs
; ++i
) {
1030 ids
[i
] = &OLSON_IDS
[i
];
1039 // ---------------------------------------
1042 TimeZone::countEquivalentIDs(const UnicodeString
& id
) {
1044 UErrorCode ec
= U_ZERO_ERROR
;
1045 UResourceBundle res
;
1046 ures_initStackObject(&res
);
1047 U_DEBUG_TZ_MSG(("countEquivalentIDs..\n"));
1048 UResourceBundle
*top
= openOlsonResource(id
, res
, ec
);
1049 if (U_SUCCESS(ec
)) {
1050 int32_t size
= ures_getSize(&res
);
1051 U_DEBUG_TZ_MSG(("cEI: success (size %d, key %s)..\n", size
, ures_getKey(&res
)));
1052 if (size
== 4 || size
== 6) {
1054 ures_initStackObject(&r
);
1055 ures_getByIndex(&res
, size
-1, &r
, &ec
);
1056 //result = ures_getSize(&r); // doesn't work
1057 ures_getIntVector(&r
, &result
, &ec
);
1058 U_DEBUG_TZ_MSG(("ceI: result %d, err %s\n", result
, u_errorName(ec
)));
1062 U_DEBUG_TZ_MSG(("cEI: fail, %s\n", u_errorName(ec
)));
1069 // ---------------------------------------
1071 const UnicodeString U_EXPORT2
1072 TimeZone::getEquivalentID(const UnicodeString
& id
, int32_t index
) {
1073 U_DEBUG_TZ_MSG(("gEI(%d)\n", index
));
1074 UnicodeString result
;
1075 UErrorCode ec
= U_ZERO_ERROR
;
1076 UResourceBundle res
;
1077 ures_initStackObject(&res
);
1078 UResourceBundle
*top
= openOlsonResource(id
, res
, ec
);
1080 if (U_SUCCESS(ec
)) {
1081 int32_t size
= ures_getSize(&res
);
1082 if (size
== 4 || size
== 6) {
1084 ures_initStackObject(&r
);
1085 ures_getByIndex(&res
, size
-1, &r
, &ec
);
1086 const int32_t* v
= ures_getIntVector(&r
, &size
, &ec
);
1087 if (index
>= 0 && index
< size
&& getOlsonMeta()) {
1095 UResourceBundle
*ares
= ures_getByKey(top
, kNAMES
, NULL
, &ec
); // dereference Zones section
1096 if (U_SUCCESS(ec
)) {
1098 const UChar
* id
= ures_getStringByIndex(ares
, zone
, &idLen
, &ec
);
1099 result
.fastCopyFrom(UnicodeString(TRUE
, id
, idLen
));
1100 U_DEBUG_TZ_MSG(("gei(%d) -> %d, len%d, %s\n", index
, zone
, result
.length(), u_errorName(ec
)));
1105 #if defined(U_DEBUG_TZ)
1106 if(result
.length() ==0) {
1107 U_DEBUG_TZ_MSG(("equiv [__, #%d] -> 0 (%s)\n", index
, u_errorName(ec
)));
1113 // ---------------------------------------
1116 TimeZone::dereferOlsonLink(const UnicodeString
& linkTo
, UnicodeString
& linkFrom
) {
1117 UErrorCode ec
= U_ZERO_ERROR
;
1119 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
1120 UResourceBundle
*res
= getZoneByName(top
, linkTo
, NULL
, ec
);
1121 if (U_SUCCESS(ec
)) {
1122 if (ures_getSize(res
) == 1) {
1123 int32_t deref
= ures_getInt(res
, &ec
);
1124 UResourceBundle
*nres
= ures_getByKey(top
, kNAMES
, NULL
, &ec
); // dereference Names section
1126 const UChar
* tmp
= ures_getStringByIndex(nres
, deref
, &len
, &ec
);
1127 if (U_SUCCESS(ec
)) {
1128 linkFrom
.setTo(tmp
, len
);
1132 linkFrom
.setTo(linkTo
);
1140 // ---------------------------------------
1144 TimeZone::getDisplayName(UnicodeString
& result
) const
1146 return getDisplayName(FALSE
,LONG
,Locale::getDefault(), result
);
1150 TimeZone::getDisplayName(const Locale
& locale
, UnicodeString
& result
) const
1152 return getDisplayName(FALSE
, LONG
, locale
, result
);
1156 TimeZone::getDisplayName(UBool daylight
, EDisplayType style
, UnicodeString
& result
) const
1158 return getDisplayName(daylight
,style
, Locale::getDefault(), result
);
1160 //--------------------------------------
1162 TimeZone::getDSTSavings()const {
1163 if (useDaylightTime()) {
1168 //---------------------------------------
1170 TimeZone::getDisplayName(UBool daylight
, EDisplayType style
, const Locale
& locale
, UnicodeString
& result
) const
1172 // SRL TODO: cache the SDF, just like java.
1173 UErrorCode status
= U_ZERO_ERROR
;
1176 fID
.extract(0, sizeof(buf
)-1, buf
, sizeof(buf
), "");
1178 SimpleDateFormat
format(style
== LONG
? ZZZZ_STR
: Z_STR
, locale
, status
);
1179 U_DEBUG_TZ_MSG(("getDisplayName(%s)\n", buf
));
1180 if(!U_SUCCESS(status
))
1184 result
.extract(0, sizeof(buf2
)-1, buf2
, sizeof(buf2
), "");
1185 U_DEBUG_TZ_MSG(("getDisplayName(%s) -> %s\n", buf
, buf2
));
1187 return result
.remove();
1190 UDate d
= Calendar::getNow();
1193 this->getOffset(d
, FALSE
, rawOffset
, dstOffset
, status
);
1194 if (U_FAILURE(status
)) {
1195 return result
.remove();
1198 if ((daylight
&& dstOffset
!= 0) || (!daylight
&& dstOffset
== 0)) {
1199 // Current time and the request (daylight / not daylight) agree.
1200 format
.setTimeZone(*this);
1201 return format
.format(d
, result
);
1204 // Create a new SimpleTimeZone as a stand-in for this zone; the
1205 // stand-in will have no DST, or DST during July, but the same ID and offset,
1206 // and hence the same display name.
1207 // We don't cache these because they're small and cheap to create.
1208 UnicodeString tempID
;
1210 SimpleTimeZone
*tz
= NULL
;
1211 if(daylight
&& useDaylightTime()){
1212 // The display name for daylight saving time was requested, but currently not in DST
1213 // Set a fixed date (July 1) in this Gregorian year
1214 GregorianCalendar
cal(*this, status
);
1215 if (U_FAILURE(status
)) {
1216 return result
.remove();
1218 cal
.set(UCAL_MONTH
, UCAL_JULY
);
1219 cal
.set(UCAL_DATE
, 1);
1222 d
= cal
.getTime(status
);
1224 // Check if it is in DST
1225 if (cal
.get(UCAL_DST_OFFSET
, status
) == 0) {
1226 // We need to create a fake time zone
1227 tz
= new SimpleTimeZone(rawOffset
, tempID
,
1229 UCAL_AUGUST
, 1, 0, 0,
1230 getDSTSavings(), status
);
1231 if (U_FAILURE(status
) || tz
== NULL
) {
1232 if (U_SUCCESS(status
)) {
1233 status
= U_MEMORY_ALLOCATION_ERROR
;
1235 return result
.remove();
1237 format
.adoptTimeZone(tz
);
1239 format
.setTimeZone(*this);
1242 // The display name for standard time was requested, but currently in DST
1243 // or display name for daylight saving time was requested, but this zone no longer
1245 tz
= new SimpleTimeZone(rawOffset
, tempID
);
1246 if (U_FAILURE(status
) || tz
== NULL
) {
1247 if (U_SUCCESS(status
)) {
1248 status
= U_MEMORY_ALLOCATION_ERROR
;
1250 return result
.remove();
1252 format
.adoptTimeZone(tz
);
1255 format
.format(d
, result
, status
);
1261 * Parse a custom time zone identifier and return a corresponding zone.
1262 * @param id a string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
1264 * @return a newly created SimpleTimeZone with the given offset and
1265 * no Daylight Savings Time, or null if the id cannot be parsed.
1268 TimeZone::createCustomTimeZone(const UnicodeString
& id
)
1270 int32_t sign
, hour
, min
, sec
;
1271 if (parseCustomID(id
, sign
, hour
, min
, sec
)) {
1272 UnicodeString customID
;
1273 formatCustomID(hour
, min
, sec
, (sign
< 0), customID
);
1274 int32_t offset
= sign
* ((hour
* 60 + min
) * 60 + sec
) * 1000;
1275 return new SimpleTimeZone(offset
, customID
);
1281 TimeZone::getCustomID(const UnicodeString
& id
, UnicodeString
& normalized
, UErrorCode
& status
) {
1282 normalized
.remove();
1283 if (U_FAILURE(status
)) {
1286 int32_t sign
, hour
, min
, sec
;
1287 if (parseCustomID(id
, sign
, hour
, min
, sec
)) {
1288 formatCustomID(hour
, min
, sec
, (sign
< 0), normalized
);
1294 TimeZone::parseCustomID(const UnicodeString
& id
, int32_t& sign
,
1295 int32_t& hour
, int32_t& min
, int32_t& sec
) {
1296 static const int32_t kParseFailed
= -99999;
1298 NumberFormat
* numberFormat
= 0;
1299 UnicodeString idUppercase
= id
;
1300 idUppercase
.toUpper();
1302 if (id
.length() > GMT_ID_LENGTH
&&
1303 idUppercase
.startsWith(GMT_ID
))
1305 ParsePosition
pos(GMT_ID_LENGTH
);
1311 if (id
[pos
.getIndex()] == MINUS
/*'-'*/) {
1313 } else if (id
[pos
.getIndex()] != PLUS
/*'+'*/) {
1316 pos
.setIndex(pos
.getIndex() + 1);
1318 UErrorCode success
= U_ZERO_ERROR
;
1319 numberFormat
= NumberFormat::createInstance(success
);
1320 if(U_FAILURE(success
)){
1323 numberFormat
->setParseIntegerOnly(TRUE
);
1324 numberFormat
->setParseStrict(FALSE
); // TODO: Really, the default should be leninet...
1326 // Look for either hh:mm, hhmm, or hh
1327 int32_t start
= pos
.getIndex();
1328 Formattable
n(kParseFailed
);
1329 numberFormat
->parse(id
, n
, pos
);
1330 if (pos
.getIndex() == start
) {
1331 delete numberFormat
;
1336 if (pos
.getIndex() < id
.length()) {
1337 if (pos
.getIndex() - start
> 2
1338 || id
[pos
.getIndex()] != 0x003A /*':'*/) {
1339 delete numberFormat
;
1343 pos
.setIndex(pos
.getIndex() + 1);
1344 int32_t oldPos
= pos
.getIndex();
1345 n
.setLong(kParseFailed
);
1346 numberFormat
->parse(id
, n
, pos
);
1347 if ((pos
.getIndex() - oldPos
) != 2) {
1349 delete numberFormat
;
1353 if (pos
.getIndex() < id
.length()) {
1354 if (id
[pos
.getIndex()] != 0x003A /*':'*/) {
1355 delete numberFormat
;
1359 pos
.setIndex(pos
.getIndex() + 1);
1360 oldPos
= pos
.getIndex();
1361 n
.setLong(kParseFailed
);
1362 numberFormat
->parse(id
, n
, pos
);
1363 if (pos
.getIndex() != id
.length()
1364 || (pos
.getIndex() - oldPos
) != 2) {
1365 delete numberFormat
;
1371 // Supported formats are below -
1380 int32_t length
= pos
.getIndex() - start
;
1381 if (length
<= 0 || 6 < length
) {
1383 delete numberFormat
;
1389 // already set to hour
1399 min
= (hour
/100) % 100;
1405 delete numberFormat
;
1407 if (hour
> kMAX_CUSTOM_HOUR
|| min
> kMAX_CUSTOM_MIN
|| sec
> kMAX_CUSTOM_SEC
) {
1416 TimeZone::formatCustomID(int32_t hour
, int32_t min
, int32_t sec
,
1417 UBool negative
, UnicodeString
& id
) {
1418 // Create time zone ID - GMT[+|-]hhmm[ss]
1420 if (hour
| min
| sec
) {
1428 id
+= (UChar
)ZERO_DIGIT
;
1430 id
+= (UChar
)(ZERO_DIGIT
+ hour
/10);
1432 id
+= (UChar
)(ZERO_DIGIT
+ hour%10
);
1435 id
+= (UChar
)ZERO_DIGIT
;
1437 id
+= (UChar
)(ZERO_DIGIT
+ min
/10);
1439 id
+= (UChar
)(ZERO_DIGIT
+ min%10
);
1443 id
+= (UChar
)ZERO_DIGIT
;
1445 id
+= (UChar
)(ZERO_DIGIT
+ sec
/10);
1447 id
+= (UChar
)(ZERO_DIGIT
+ sec%10
);
1455 TimeZone::hasSameRules(const TimeZone
& other
) const
1457 return (getRawOffset() == other
.getRawOffset() &&
1458 useDaylightTime() == other
.useDaylightTime());
1462 TimeZone::getTZDataVersion(UErrorCode
& status
)
1464 /* This is here to prevent race conditions. */
1466 UMTX_CHECK(&LOCK
, (TZDATA_VERSION
[0] == 0), needsInit
);
1468 int32_t len
= sizeof(TZDATA_VERSION
);
1469 UResourceBundle
*bundle
= ures_openDirect(NULL
, "zoneinfo", &status
);
1470 const UChar
*tzver
= ures_getStringByKey(bundle
, "TZVersion",
1474 if (U_SUCCESS(status
)) {
1475 u_UCharsToChars(tzver
, TZDATA_VERSION
, len
+1);
1476 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
1482 if (U_FAILURE(status
)) {
1485 return (const char*)TZDATA_VERSION
;
1489 TimeZone::getCanonicalID(const UnicodeString
& id
, UnicodeString
& canonicalID
, UErrorCode
& status
)
1491 UBool isSystemID
= FALSE
;
1492 return getCanonicalID(id
, canonicalID
, isSystemID
, status
);
1496 TimeZone::getCanonicalID(const UnicodeString
& id
, UnicodeString
& canonicalID
, UBool
& isSystemID
,
1499 canonicalID
.remove();
1501 if (U_FAILURE(status
)) {
1504 ZoneMeta::getCanonicalSystemID(id
, canonicalID
, status
);
1505 if (U_SUCCESS(status
)) {
1509 status
= U_ZERO_ERROR
;
1510 getCustomID(id
, canonicalID
, status
);
1517 #endif /* #if !UCONFIG_NO_FORMATTING */