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 * 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"
83 #define kZONEINFO "zoneinfo"
84 #define kREGIONS "Regions"
85 #define kZONES "Zones"
86 #define kRULES "Rules"
87 #define kNAMES "Names"
88 #define kDEFAULT "Default"
90 // Static data and constants
92 static const UChar GMT_ID
[] = {0x47, 0x4D, 0x54, 0x00}; /* "GMT" */
93 static const UChar Z_STR
[] = {0x7A, 0x00}; /* "z" */
94 static const UChar ZZZZ_STR
[] = {0x7A, 0x7A, 0x7A, 0x7A, 0x00}; /* "zzzz" */
95 static const int32_t GMT_ID_LENGTH
= 3;
96 static const UChar CUSTOM_ID
[] =
98 0x43, 0x75, 0x73, 0x74, 0x6F, 0x6D, 0x00 /* "Custom" */
102 static TimeZone
* DEFAULT_ZONE
= NULL
;
103 static TimeZone
* _GMT
= NULL
; // cf. TimeZone::GMT
105 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
106 static UnicodeString
* OLSON_IDS
= 0;
110 static UBool U_CALLCONV
timeZone_cleanup()
112 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
135 * The Olson data is stored the "zoneinfo" resource bundle.
136 * Sub-resources are organized into three ranges of data: Zones, final
137 * rules, and country tables. There is also a meta-data resource
138 * which has 3 integers: The number of zones, rules, and countries,
139 * respectively. The country count includes the non-country 'Default'.
141 static int32_t OLSON_ZONE_START
= -1; // starting index of zones
142 static int32_t OLSON_ZONE_COUNT
= 0; // count of zones
145 * Given a pointer to an open "zoneinfo" resource, load up the Olson
146 * meta-data. Return TRUE if successful.
148 static UBool
getOlsonMeta(const UResourceBundle
* top
) {
149 if (OLSON_ZONE_START
< 0) {
150 UErrorCode ec
= U_ZERO_ERROR
;
152 ures_initStackObject(&res
);
153 ures_getByKey(top
, kZONES
, &res
, &ec
);
155 OLSON_ZONE_COUNT
= ures_getSize(&res
);
156 OLSON_ZONE_START
= 0;
157 U_DEBUG_TZ_MSG(("OZC%d OZS%d\n",OLSON_ZONE_COUNT
, OLSON_ZONE_START
));
161 return (OLSON_ZONE_START
>= 0);
165 * Load up the Olson meta-data. Return TRUE if successful.
167 static UBool
getOlsonMeta() {
168 if (OLSON_ZONE_START
< 0) {
169 UErrorCode ec
= U_ZERO_ERROR
;
170 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
176 return (OLSON_ZONE_START
>= 0);
179 static int32_t findInStringArray(UResourceBundle
* array
, const UnicodeString
& id
, UErrorCode
&status
)
182 copy
.fastCopyFrom(id
);
183 const UChar
* buf
= copy
.getTerminatedBuffer();
184 const UChar
* u
= NULL
;
186 int32_t count
= ures_getSize(array
);
190 int32_t limit
= count
;
191 if(U_FAILURE(status
) || (count
< 1)) {
194 U_DEBUG_TZ_MSG(("fisa: Looking for %s, between %d and %d\n", U_DEBUG_TZ_STR(buf
), start
, limit
));
196 while(U_SUCCESS(status
) && (start
<limit
-1)) {
197 i
= (int32_t)((start
+limit
)/2);
198 u
= ures_getStringByIndex(array
, i
, &len
, &status
);
199 U_DEBUG_TZ_MSG(("tz: compare to %s, %d .. [%d] .. %d\n", U_DEBUG_TZ_STR(u
), start
, i
, limit
));
200 int r
= u_strcmp(buf
,u
);
201 if((r
==0) && U_SUCCESS(status
)) {
202 U_DEBUG_TZ_MSG(("fisa: found at %d\n", i
));
210 u
= ures_getStringByIndex(array
, start
, &len
, &status
);
211 if(u_strcmp(buf
,u
)==0) {
212 U_DEBUG_TZ_MSG(("fisa: finally found at %d\n", start
));
215 U_DEBUG_TZ_MSG(("fisa: not found\n"));
220 * Fetch a specific zone by name. Replaces the getByKey call.
221 * @param top Top timezone resource
222 * @param id Time zone ID
223 * @param oldbundle Bundle for reuse (or NULL). see 'ures_open()'
224 * @return the zone's bundle if found, or undefined if error. Reuses oldbundle.
226 static UResourceBundle
* getZoneByName(const UResourceBundle
* top
, const UnicodeString
& id
, UResourceBundle
*oldbundle
, UErrorCode
& status
) {
227 // load the Rules object
228 UResourceBundle
*tmp
= ures_getByKey(top
, kNAMES
, NULL
, &status
);
230 // search for the string
231 int32_t idx
= findInStringArray(tmp
, id
, status
);
233 if((idx
== -1) && U_SUCCESS(status
)) {
235 status
= U_MISSING_RESOURCE_ERROR
;
236 //ures_close(oldbundle);
239 U_DEBUG_TZ_MSG(("gzbn: oldbundle= size %d, type %d, %s\n", ures_getSize(tmp
), ures_getType(tmp
), u_errorName(status
)));
240 tmp
= ures_getByKey(top
, kZONES
, tmp
, &status
); // get Zones object from top
241 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
)));
242 oldbundle
= ures_getByIndex(tmp
, idx
, oldbundle
, &status
); // get nth Zone object
243 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
)));
246 if(U_FAILURE(status
)) {
247 //ures_close(oldbundle);
255 UResourceBundle
* TimeZone::loadRule(const UResourceBundle
* top
, const UnicodeString
& ruleid
, UResourceBundle
* oldbundle
, UErrorCode
& status
) {
257 ruleid
.extract(0, sizeof(key
)-1, key
, (int32_t)sizeof(key
)-1, US_INV
);
258 U_DEBUG_TZ_MSG(("loadRule(%s)\n", key
));
259 UResourceBundle
*r
= ures_getByKey(top
, kRULES
, oldbundle
, &status
);
260 U_DEBUG_TZ_MSG(("loadRule(%s) -> kRULES [%s]\n", key
, u_errorName(status
)));
261 r
= ures_getByKey(r
, key
, r
, &status
);
262 U_DEBUG_TZ_MSG(("loadRule(%s) -> item [%s]\n", key
, u_errorName(status
)));
267 * Given an ID, open the appropriate resource for the given time zone.
268 * Dereference aliases if necessary.
270 * @param res resource, which must be ready for use (initialized but not open)
271 * @param ec input-output error code
272 * @return top-level resource bundle
274 static UResourceBundle
* openOlsonResource(const UnicodeString
& id
,
275 UResourceBundle
& res
,
280 id
.extract(0, sizeof(buf
)-1, buf
, sizeof(buf
), "");
282 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
283 U_DEBUG_TZ_MSG(("pre: res sz=%d\n", ures_getSize(&res
)));
284 /* &res = */ getZoneByName(top
, id
, &res
, ec
);
285 // Dereference if this is an alias. Docs say result should be 1
286 // but it is 0 in 2.8 (?).
287 U_DEBUG_TZ_MSG(("Loading zone '%s' (%s, size %d) - %s\n", buf
, ures_getKey((UResourceBundle
*)&res
), ures_getSize(&res
), u_errorName(ec
)));
288 if (ures_getSize(&res
) <= 1 && getOlsonMeta(top
)) {
289 int32_t deref
= ures_getInt(&res
, &ec
) + 0;
290 U_DEBUG_TZ_MSG(("getInt: %s - type is %d\n", u_errorName(ec
), ures_getType(&res
)));
291 UResourceBundle
*ares
= ures_getByKey(top
, kZONES
, NULL
, &ec
); // dereference Zones section
292 ures_getByIndex(ares
, deref
, &res
, &ec
);
294 U_DEBUG_TZ_MSG(("alias to #%d (%s) - %s\n", deref
, "??", u_errorName(ec
)));
296 U_DEBUG_TZ_MSG(("not an alias - size %d\n", ures_getSize(&res
)));
298 U_DEBUG_TZ_MSG(("%s - final status is %s\n", buf
, u_errorName(ec
)));
302 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
305 * Load all the ids from the "zoneinfo" resource bundle into a static
306 * array that we hang onto. This is _only_ used to implement the
307 * deprecated createAvailableIDs() API.
309 static UBool
loadOlsonIDs() {
310 if (OLSON_IDS
!= 0) {
314 UErrorCode ec
= U_ZERO_ERROR
;
315 UnicodeString
* ids
= 0;
317 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
318 UResourceBundle
*nres
= ures_getByKey(top
, kNAMES
, NULL
, &ec
); // dereference Names section
322 count
= ures_getSize(nres
);
323 ids
= new UnicodeString
[(count
> 0) ? count
: 1];
324 for (int32_t i
=0; i
<count
; ++i
) {
326 const UChar
* id
= ures_getStringByIndex(nres
, i
, &idLen
, &ec
);
327 ids
[i
].fastCopyFrom(UnicodeString(TRUE
, id
, idLen
));
341 // Keep mutexed operations as short as possible by doing all
342 // computations first, then doing pointer copies within the mutex.
344 if (OLSON_IDS
== 0) {
347 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
351 // If another thread initialized the statics first, then delete
359 // -------------------------------------
361 const TimeZone
* U_EXPORT2
362 TimeZone::getGMT(void)
364 umtx_init(&LOCK
); /* This is here to prevent race conditions. */
366 // Initialize _GMT independently of other static data; it should
367 // be valid even if we can't load the time zone UDataMemory.
369 _GMT
= new SimpleTimeZone(0, UnicodeString(GMT_ID
, GMT_ID_LENGTH
));
370 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
375 // *****************************************************************************
377 // *****************************************************************************
379 UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(TimeZone
)
386 // -------------------------------------
388 TimeZone::TimeZone(const UnicodeString
&id
)
393 // -------------------------------------
395 TimeZone::~TimeZone()
399 // -------------------------------------
401 TimeZone::TimeZone(const TimeZone
&source
)
402 : UObject(source
), fID(source
.fID
)
406 // -------------------------------------
409 TimeZone::operator=(const TimeZone
&right
)
411 if (this != &right
) fID
= right
.fID
;
415 // -------------------------------------
418 TimeZone::operator==(const TimeZone
& that
) const
420 return getDynamicClassID() == that
.getDynamicClassID() &&
424 // -------------------------------------
427 TimeZone::createTimeZone(const UnicodeString
& ID
)
429 /* We first try to lookup the zone ID in our system list. If this
430 * fails, we try to parse it as a custom string GMT[+-]hh:mm. If
431 * all else fails, we return GMT, which is probably not what the
432 * user wants, but at least is a functioning TimeZone object.
434 * We cannot return NULL, because that would break compatibility
437 TimeZone
* result
= createSystemTimeZone(ID
);
440 U_DEBUG_TZ_MSG(("failed to load system time zone with id - falling to custom"));
441 result
= createCustomTimeZone(ID
);
444 U_DEBUG_TZ_MSG(("failed to load time zone with id - falling to GMT"));
445 result
= getGMT()->clone();
451 * Lookup the given name in our system zone table. If found,
452 * instantiate a new zone of that name and return it. If not
456 TimeZone::createSystemTimeZone(const UnicodeString
& id
) {
458 UErrorCode ec
= U_ZERO_ERROR
;
460 ures_initStackObject(&res
);
461 U_DEBUG_TZ_MSG(("pre-err=%s\n", u_errorName(ec
)));
462 UResourceBundle
*top
= openOlsonResource(id
, res
, ec
);
463 U_DEBUG_TZ_MSG(("post-err=%s\n", u_errorName(ec
)));
465 z
= new OlsonTimeZone(top
, &res
, ec
);
469 U_DEBUG_TZ_MSG(("cstz: olson time zone failed to initialize - err %s\n", u_errorName(ec
)));
475 U_DEBUG_TZ_MSG(("cstz: failed to create, err %s\n", u_errorName(ec
)));
482 // -------------------------------------
485 * Initialize DEFAULT_ZONE from the system default time zone. The
486 * caller should confirm that DEFAULT_ZONE is NULL before calling.
487 * Upon return, DEFAULT_ZONE will not be NULL, unless operator new()
490 * Must be called OUTSIDE mutex.
493 TimeZone::initDefault()
495 // We access system timezone data through TPlatformUtilities,
496 // including tzset(), timezone, and tzname[].
497 int32_t rawOffset
= 0;
500 // First, try to create a system timezone, based
501 // on the string ID in tzname[0].
503 // NOTE: Global mutex here; TimeZone mutex above
504 // mutexed to avoid threading issues in the platform fcns.
505 // Some of the locale/timezone OS functions may not be thread safe,
506 // so the intent is that any setting from anywhere within ICU
507 // happens with the ICU global mutex held.
509 uprv_tzset(); // Initialize tz... system data
511 // Get the timezone ID from the host. This function should do
512 // any required host-specific remapping; e.g., on Windows this
513 // function maps the Date and Time control panel setting to an
515 hostID
= uprv_tzname(0);
517 // Invert sign because UNIX semantics are backwards
518 rawOffset
= uprv_timezone() * -U_MILLIS_PER_SECOND
;
521 TimeZone
* default_zone
= NULL
;
523 /* Make sure that the string is NULL terminated to prevent BoundsChecker/Purify warnings. */
524 UnicodeString
hostStrID(hostID
, -1, US_INV
);
525 hostStrID
.append((UChar
)0);
526 hostStrID
.truncate(hostStrID
.length()-1);
527 default_zone
= createSystemTimeZone(hostStrID
);
530 // NOTE: As of ICU 2.8, we no longer have an offsets table, since
531 // historical zones can change offset over time. If we add
532 // build-time heuristics to infer the "most frequent" raw offset
533 // of a zone, we can build tables and institute defaults, as done
536 // If we couldn't get the time zone ID from the host, use
537 // the default host timezone offset. Further refinements
538 // to this include querying the host to determine if DST
539 // is in use or not and possibly using the host locale to
540 // select from multiple zones at a the same offset. We
541 // don't do any of this now, but we could easily add this.
542 if (default_zone
== NULL
) {
543 // Use the designated default in the time zone list that has the
544 // appropriate GMT offset, if there is one.
546 const OffsetIndex
* index
= INDEX_BY_OFFSET
;
549 if (index
->gmtOffset
> rawOffset
) {
550 // Went past our desired offset; no match found
553 if (index
->gmtOffset
== rawOffset
) {
554 // Found our desired offset
555 default_zone
= createSystemTimeZone(ZONE_IDS
[index
->defaultZone
]);
558 // Compute the position of the next entry. If the delta value
559 // in this entry is zero, then there is no next entry.
560 uint16_t delta
= index
->nextEntryDelta
;
564 index
= (const OffsetIndex
*)((int8_t*)index
+ delta
);
569 // Construct a fixed standard zone with the host's ID
571 if (default_zone
== NULL
) {
572 default_zone
= new SimpleTimeZone(rawOffset
, hostStrID
);
575 // If we _still_ don't have a time zone, use GMT.
576 if (default_zone
== NULL
) {
577 default_zone
= getGMT()->clone();
580 // If DEFAULT_ZONE is still NULL, set it up.
582 if (DEFAULT_ZONE
== NULL
) {
583 DEFAULT_ZONE
= default_zone
;
585 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
592 // -------------------------------------
595 TimeZone::createDefault()
597 umtx_init(&LOCK
); /* This is here to prevent race conditions. */
599 UBool f
= (DEFAULT_ZONE
!= 0);
605 Mutex
lock(&LOCK
); // In case adoptDefault is called
606 return DEFAULT_ZONE
->clone();
609 // -------------------------------------
612 TimeZone::adoptDefault(TimeZone
* zone
)
616 TimeZone
* old
= NULL
;
618 umtx_init(&LOCK
); /* This is here to prevent race conditions. */
625 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
628 // -------------------------------------
631 TimeZone::setDefault(const TimeZone
& zone
)
633 adoptDefault(zone
.clone());
636 //----------------------------------------------------------------------
639 * This is the default implementation for subclasses that do not
640 * override this method. This implementation calls through to the
641 * 8-argument getOffset() method after suitable computations, and
642 * correctly adjusts GMT millis to local millis when necessary.
644 void TimeZone::getOffset(UDate date
, UBool local
, int32_t& rawOffset
,
645 int32_t& dstOffset
, UErrorCode
& ec
) const {
650 rawOffset
= getRawOffset();
652 // Convert to local wall millis if necessary
654 date
+= rawOffset
; // now in local standard millis
657 // When local==FALSE, we might have to recompute. This loop is
658 // executed once, unless a recomputation is required; then it is
660 for (int32_t pass
=0; ; ++pass
) {
661 int32_t year
, month
, dom
, dow
;
662 double day
= uprv_floor(date
/ U_MILLIS_PER_DAY
);
663 int32_t millis
= (int32_t) (date
- day
* U_MILLIS_PER_DAY
);
665 Grego::dayToFields(day
, year
, month
, dom
, dow
);
667 dstOffset
= getOffset(GregorianCalendar::AD
, year
, month
, dom
,
668 (uint8_t) dow
, millis
,
669 Grego::monthLength(year
, month
),
672 // Recompute if local==FALSE, dstOffset!=0, and addition of
673 // the dstOffset puts us in a different day.
674 if (pass
!=0 || local
|| dstOffset
==0) {
678 if (uprv_floor(date
/ U_MILLIS_PER_DAY
) == day
) {
684 // -------------------------------------
686 // New available IDs API as of ICU 2.4. Uses StringEnumeration API.
688 class TZEnumeration
: public StringEnumeration
{
689 // Map into to zones. Our results are zone[map[i]] for
690 // i=0..len-1, where zone[i] is the i-th Olson zone. If map==NULL
691 // then our results are zone[i] for i=0..len-1. Len will be zero
692 // iff the zone data could not be loaded.
698 TZEnumeration() : map(NULL
), len(0), pos(0) {
699 if (getOlsonMeta()) {
700 len
= OLSON_ZONE_COUNT
;
704 TZEnumeration(int32_t rawOffset
) : map(NULL
), len(0), pos(0) {
705 if (!getOlsonMeta()) {
709 // Allocate more space than we'll need. The end of the array will
711 map
= (int32_t*)uprv_malloc(OLSON_ZONE_COUNT
* sizeof(int32_t));
716 uprv_memset(map
, 0, sizeof(int32_t) * OLSON_ZONE_COUNT
);
719 for (int32_t i
=0; i
<OLSON_ZONE_COUNT
; ++i
) {
721 // This is VERY inefficient.
722 TimeZone
* z
= TimeZone::createTimeZone(unistr
);
723 // Make sure we get back the ID we wanted (if the ID is
724 // invalid we get back GMT).
725 if (z
!= 0 && z
->getID(s
) == unistr
&&
726 z
->getRawOffset() == rawOffset
) {
734 TZEnumeration(const char* country
) : map(NULL
), len(0), pos(0) {
735 if (!getOlsonMeta()) {
739 char key
[] = {0, 0, 0, 0,0, 0, 0,0, 0, 0,0}; // e.g., "US", or "Default" for no country
741 uprv_strncat(key
, country
, 2);
743 uprv_strcpy(key
, kDEFAULT
);
746 UErrorCode ec
= U_ZERO_ERROR
;
747 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
748 top
= ures_getByKey(top
, kREGIONS
, top
, &ec
); // dereference 'Regions' section
751 ures_initStackObject(&res
);
752 ures_getByKey(top
, key
, &res
, &ec
);
753 // The list of zones is a list of integers, from 0..n-1,
754 // where n is the total number of system zones.
755 const int32_t* v
= ures_getIntVector(&res
, &len
, &ec
);
758 map
= (int32_t*)uprv_malloc(sizeof(int32_t) * len
);
760 for (uint16_t i
=0; i
<len
; ++i
) {
761 U_ASSERT(v
[i
] >= 0 && v
[i
] < OLSON_ZONE_COUNT
);
766 U_DEBUG_TZ_MSG(("Failed to load tz for region %s: %s\n", country
, u_errorName(ec
)));
773 TZEnumeration(const TZEnumeration
&other
) : StringEnumeration(), map(NULL
), len(0), pos(0) {
775 if(other
.map
!= NULL
) {
776 map
= (int32_t *)uprv_malloc(other
.len
* sizeof(int32_t));
779 uprv_memcpy(map
, other
.map
, len
* sizeof(int32_t));
789 virtual ~TZEnumeration() {
793 virtual StringEnumeration
*clone() const {
794 return new TZEnumeration(*this);
797 virtual int32_t count(UErrorCode
& status
) const {
798 return U_FAILURE(status
) ? 0 : len
;
801 virtual const UnicodeString
* snext(UErrorCode
& status
) {
802 if (U_SUCCESS(status
) && pos
< len
) {
803 getID((map
== 0) ? pos
: map
[pos
]);
810 virtual void reset(UErrorCode
& /*status*/) {
816 UBool
getID(int32_t i
) {
817 UErrorCode ec
= U_ZERO_ERROR
;
819 const UChar
* id
= NULL
;
820 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
821 top
= ures_getByKey(top
, kNAMES
, top
, &ec
); // dereference Zones section
822 id
= ures_getStringByIndex(top
, i
, &idLen
, &ec
);
827 unistr
.fastCopyFrom(UnicodeString(TRUE
, id
, idLen
));
830 return U_SUCCESS(ec
);
834 static UClassID U_EXPORT2
getStaticClassID(void);
835 virtual UClassID
getDynamicClassID(void) const;
838 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TZEnumeration
)
840 StringEnumeration
* U_EXPORT2
841 TimeZone::createEnumeration() {
842 return new TZEnumeration();
845 StringEnumeration
* U_EXPORT2
846 TimeZone::createEnumeration(int32_t rawOffset
) {
847 return new TZEnumeration(rawOffset
);
850 StringEnumeration
* U_EXPORT2
851 TimeZone::createEnumeration(const char* country
) {
852 return new TZEnumeration(country
);
855 // -------------------------------------
857 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
859 const UnicodeString
**
860 TimeZone::createAvailableIDs(int32_t rawOffset
, int32_t& numIDs
)
862 // We are creating a new array to existing UnicodeString pointers.
863 // The caller will delete the array when done, but not the pointers
867 if (!loadOlsonIDs()) {
871 // Allocate more space than we'll need. The end of the array will
873 const UnicodeString
** ids
=
874 (const UnicodeString
** )uprv_malloc(OLSON_ZONE_COUNT
* sizeof(UnicodeString
*));
879 uprv_memset(ids
, 0, sizeof(UnicodeString
*) * OLSON_ZONE_COUNT
);
882 for (int32_t i
=0; i
<OLSON_ZONE_COUNT
; ++i
) {
883 // This is VERY inefficient.
884 TimeZone
* z
= TimeZone::createTimeZone(OLSON_IDS
[i
]);
885 // Make sure we get back the ID we wanted (if the ID is
886 // invalid we get back GMT).
887 if (z
!= 0 && z
->getID(s
) == OLSON_IDS
[i
] &&
888 z
->getRawOffset() == rawOffset
) {
889 ids
[numIDs
++] = &OLSON_IDS
[i
]; // [sic]
897 // -------------------------------------
899 const UnicodeString
**
900 TimeZone::createAvailableIDs(const char* country
, int32_t& numIDs
) {
902 // We are creating a new array to existing UnicodeString pointers.
903 // The caller will delete the array when done, but not the pointers
907 if (!loadOlsonIDs()) {
911 char key
[] = { 0, 0, 0,0, 0, 0,0, 0, 0 }; // e.g., "US", or "Default" for non-country zones
913 uprv_strncat(key
, country
, 2);
915 uprv_strcpy(key
, kDEFAULT
);
918 const UnicodeString
** ids
= 0;
920 UErrorCode ec
= U_ZERO_ERROR
;
921 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
922 UResourceBundle
*ares
= ures_getByKey(top
, kREGIONS
, NULL
, &ec
); // dereference Regions section
926 ures_initStackObject(&res
);
927 ures_getByKey(ares
, key
, &res
, &ec
);
928 U_DEBUG_TZ_MSG(("caI: on %s, err %s\n", country
, u_errorName(ec
)));
930 /* The list of zones is a list of integers, from 0..n-1,
931 * where n is the total number of system zones. The
932 * numbering corresponds exactly to the ordering of
935 const int32_t* v
= ures_getIntVector(&res
, &numIDs
, &ec
);
936 ids
= (const UnicodeString
**)
937 uprv_malloc(numIDs
* sizeof(UnicodeString
*));
941 for (int32_t i
=0; i
<numIDs
; ++i
) {
942 ids
[i
] = &OLSON_IDS
[v
[i
]]; // [sic]
954 // -------------------------------------
956 const UnicodeString
**
957 TimeZone::createAvailableIDs(int32_t& numIDs
)
959 // We are creating a new array to existing UnicodeString pointers.
960 // The caller will delete the array when done, but not the pointers
963 if (!loadOlsonIDs()) {
967 const UnicodeString
** ids
=
968 (const UnicodeString
** )uprv_malloc(OLSON_ZONE_COUNT
* sizeof(UnicodeString
*));
970 numIDs
= OLSON_ZONE_COUNT
;
971 for (int32_t i
=0; i
<numIDs
; ++i
) {
972 ids
[i
] = &OLSON_IDS
[i
];
981 // ---------------------------------------
984 TimeZone::countEquivalentIDs(const UnicodeString
& id
) {
986 UErrorCode ec
= U_ZERO_ERROR
;
988 ures_initStackObject(&res
);
989 U_DEBUG_TZ_MSG(("countEquivalentIDs..\n"));
990 UResourceBundle
*top
= openOlsonResource(id
, res
, ec
);
992 int32_t size
= ures_getSize(&res
);
993 U_DEBUG_TZ_MSG(("cEI: success (size %d, key %s)..\n", size
, ures_getKey(&res
)));
994 if (size
== 4 || size
== 6) {
996 ures_initStackObject(&r
);
997 ures_getByIndex(&res
, size
-1, &r
, &ec
);
998 //result = ures_getSize(&r); // doesn't work
999 ures_getIntVector(&r
, &result
, &ec
);
1000 U_DEBUG_TZ_MSG(("ceI: result %d, err %s\n", result
, u_errorName(ec
)));
1004 U_DEBUG_TZ_MSG(("cEI: fail, %s\n", u_errorName(ec
)));
1011 // ---------------------------------------
1013 const UnicodeString U_EXPORT2
1014 TimeZone::getEquivalentID(const UnicodeString
& id
, int32_t index
) {
1015 U_DEBUG_TZ_MSG(("gEI(%d)\n", index
));
1016 UnicodeString result
;
1017 UErrorCode ec
= U_ZERO_ERROR
;
1018 UResourceBundle res
;
1019 ures_initStackObject(&res
);
1020 UResourceBundle
*top
= openOlsonResource(id
, res
, ec
);
1022 if (U_SUCCESS(ec
)) {
1023 int32_t size
= ures_getSize(&res
);
1024 if (size
== 4 || size
== 6) {
1026 ures_initStackObject(&r
);
1027 ures_getByIndex(&res
, size
-1, &r
, &ec
);
1028 const int32_t* v
= ures_getIntVector(&r
, &size
, &ec
);
1029 if (index
>= 0 && index
< size
&& getOlsonMeta()) {
1037 UResourceBundle
*ares
= ures_getByKey(top
, kNAMES
, NULL
, &ec
); // dereference Zones section
1038 if (U_SUCCESS(ec
)) {
1040 const UChar
* id
= ures_getStringByIndex(ares
, zone
, &idLen
, &ec
);
1041 result
.fastCopyFrom(UnicodeString(TRUE
, id
, idLen
));
1042 U_DEBUG_TZ_MSG(("gei(%d) -> %d, len%d, %s\n", index
, zone
, result
.length(), u_errorName(ec
)));
1047 #if defined(U_DEBUG_TZ)
1048 if(result
.length() ==0) {
1049 U_DEBUG_TZ_MSG(("equiv [__, #%d] -> 0 (%s)\n", index
, u_errorName(ec
)));
1055 // ---------------------------------------
1059 TimeZone::getDisplayName(UnicodeString
& result
) const
1061 return getDisplayName(FALSE
,LONG
,Locale::getDefault(), result
);
1065 TimeZone::getDisplayName(const Locale
& locale
, UnicodeString
& result
) const
1067 return getDisplayName(FALSE
, LONG
, locale
, result
);
1071 TimeZone::getDisplayName(UBool daylight
, EDisplayType style
, UnicodeString
& result
) const
1073 return getDisplayName(daylight
,style
, Locale::getDefault(), result
);
1077 TimeZone::getDisplayName(UBool daylight
, EDisplayType style
, const Locale
& locale
, UnicodeString
& result
) const
1079 // SRL TODO: cache the SDF, just like java.
1080 UErrorCode status
= U_ZERO_ERROR
;
1083 fID
.extract(0, sizeof(buf
)-1, buf
, sizeof(buf
), "");
1085 SimpleDateFormat
format(style
== LONG
? ZZZZ_STR
: Z_STR
,locale
,status
);
1086 U_DEBUG_TZ_MSG(("getDisplayName(%s)\n", buf
));
1087 if(!U_SUCCESS(status
))
1091 result
.extract(0, sizeof(buf2
)-1, buf2
, sizeof(buf2
), "");
1092 U_DEBUG_TZ_MSG(("getDisplayName(%s) -> %s\n", buf
, buf2
));
1094 return result
.remove();
1097 // Create a new SimpleTimeZone as a stand-in for this zone; the
1098 // stand-in will have no DST, or all DST, but the same ID and offset,
1099 // and hence the same display name.
1100 // We don't cache these because they're small and cheap to create.
1101 UnicodeString tempID
;
1102 SimpleTimeZone
*tz
= daylight
?
1103 // For the pure-DST zone, we use JANUARY and DECEMBER
1105 new SimpleTimeZone(getRawOffset(), getID(tempID
),
1106 UCAL_JANUARY
, 1, 0, 0,
1107 UCAL_DECEMBER
, 31, 0, U_MILLIS_PER_DAY
, status
) :
1108 new SimpleTimeZone(getRawOffset(), getID(tempID
));
1110 format
.applyPattern(style
== LONG
? ZZZZ_STR
: Z_STR
);
1111 Calendar
*myCalendar
= (Calendar
*)format
.getCalendar();
1112 myCalendar
->setTimeZone(*tz
); // copy
1116 FieldPosition
pos(FieldPosition::DONT_CARE
);
1117 return format
.format(UDate(196262345678.), result
, pos
); // Must use a valid date here.
1122 * Parse a custom time zone identifier and return a corresponding zone.
1123 * @param id a string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
1125 * @return a newly created SimpleTimeZone with the given offset and
1126 * no Daylight Savings Time, or null if the id cannot be parsed.
1129 TimeZone::createCustomTimeZone(const UnicodeString
& id
)
1131 static const int32_t kParseFailed
= -99999;
1133 NumberFormat
* numberFormat
= 0;
1135 UnicodeString idUppercase
= id
;
1136 idUppercase
.toUpper();
1138 if (id
.length() > GMT_ID_LENGTH
&&
1139 idUppercase
.startsWith(GMT_ID
))
1141 ParsePosition
pos(GMT_ID_LENGTH
);
1142 UBool negative
= FALSE
;
1145 if (id
[pos
.getIndex()] == 0x002D /*'-'*/)
1147 else if (id
[pos
.getIndex()] != 0x002B /*'+'*/)
1149 pos
.setIndex(pos
.getIndex() + 1);
1151 UErrorCode success
= U_ZERO_ERROR
;
1152 numberFormat
= NumberFormat::createInstance(success
);
1153 numberFormat
->setParseIntegerOnly(TRUE
);
1156 // Look for either hh:mm, hhmm, or hh
1157 int32_t start
= pos
.getIndex();
1159 Formattable
n(kParseFailed
);
1161 numberFormat
->parse(id
, n
, pos
);
1162 if (pos
.getIndex() == start
) {
1163 delete numberFormat
;
1166 offset
= n
.getLong();
1168 if (pos
.getIndex() < id
.length() &&
1169 id
[pos
.getIndex()] == 0x003A /*':'*/)
1173 pos
.setIndex(pos
.getIndex() + 1);
1174 int32_t oldPos
= pos
.getIndex();
1175 n
.setLong(kParseFailed
);
1176 numberFormat
->parse(id
, n
, pos
);
1177 if (pos
.getIndex() == oldPos
) {
1178 delete numberFormat
;
1181 offset
+= n
.getLong();
1187 // Be strict about interpreting something as hh; it must be
1188 // an offset < 30, and it must be one or two digits. Thus
1189 // 0010 is interpreted as 00:10, but 10 is interpreted as
1191 if (offset
< 30 && (pos
.getIndex() - start
) <= 2)
1192 offset
*= 60; // hh, from 00 to 29; 30 is 00:30
1194 offset
= offset
% 100 + offset
/ 100 * 60; // hhmm
1200 delete numberFormat
;
1201 return new SimpleTimeZone(offset
* 60000, CUSTOM_ID
);
1208 TimeZone::hasSameRules(const TimeZone
& other
) const
1210 return (getRawOffset() == other
.getRawOffset() &&
1211 useDaylightTime() == other
.useDaylightTime());
1216 #endif /* #if !UCONFIG_NO_FORMATTING */