2 *******************************************************************************
3 * Copyright (C) 1997-2006, 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(void)
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
)
186 int32_t limit
= ures_getSize(array
);
188 int32_t lastMid
= INT32_MAX
;
189 if(U_FAILURE(status
) || (limit
< 1)) {
192 U_DEBUG_TZ_MSG(("fisa: Looking for %s, between %d and %d\n", U_DEBUG_TZ_STR(UnicodeString(id
).getTerminatedBuffer()), start
, limit
));
195 mid
= (int32_t)((start
+ limit
) / 2);
196 if (lastMid
== mid
) { /* Have we moved? */
197 break; /* We haven't moved, and it wasn't found. */
200 u
= ures_getStringByIndex(array
, mid
, &len
, &status
);
201 if (U_FAILURE(status
)) {
204 U_DEBUG_TZ_MSG(("tz: compare to %s, %d .. [%d] .. %d\n", U_DEBUG_TZ_STR(u
), start
, mid
, limit
));
205 copy
.setTo(TRUE
, u
, len
);
206 int r
= id
.compare(copy
);
208 U_DEBUG_TZ_MSG(("fisa: found at %d\n", mid
));
216 U_DEBUG_TZ_MSG(("fisa: not found\n"));
221 * Fetch a specific zone by name. Replaces the getByKey call.
222 * @param top Top timezone resource
223 * @param id Time zone ID
224 * @param oldbundle Bundle for reuse (or NULL). see 'ures_open()'
225 * @return the zone's bundle if found, or undefined if error. Reuses oldbundle.
227 static UResourceBundle
* getZoneByName(const UResourceBundle
* top
, const UnicodeString
& id
, UResourceBundle
*oldbundle
, UErrorCode
& status
) {
228 // load the Rules object
229 UResourceBundle
*tmp
= ures_getByKey(top
, kNAMES
, NULL
, &status
);
231 // search for the string
232 int32_t idx
= findInStringArray(tmp
, id
, status
);
234 if((idx
== -1) && U_SUCCESS(status
)) {
236 status
= U_MISSING_RESOURCE_ERROR
;
237 //ures_close(oldbundle);
240 U_DEBUG_TZ_MSG(("gzbn: oldbundle= size %d, type %d, %s\n", ures_getSize(tmp
), ures_getType(tmp
), u_errorName(status
)));
241 tmp
= ures_getByKey(top
, kZONES
, tmp
, &status
); // get Zones object from top
242 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
)));
243 oldbundle
= ures_getByIndex(tmp
, idx
, oldbundle
, &status
); // get nth Zone object
244 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
)));
247 if(U_FAILURE(status
)) {
248 //ures_close(oldbundle);
256 UResourceBundle
* TimeZone::loadRule(const UResourceBundle
* top
, const UnicodeString
& ruleid
, UResourceBundle
* oldbundle
, UErrorCode
& status
) {
258 ruleid
.extract(0, sizeof(key
)-1, key
, (int32_t)sizeof(key
)-1, US_INV
);
259 U_DEBUG_TZ_MSG(("loadRule(%s)\n", key
));
260 UResourceBundle
*r
= ures_getByKey(top
, kRULES
, oldbundle
, &status
);
261 U_DEBUG_TZ_MSG(("loadRule(%s) -> kRULES [%s]\n", key
, u_errorName(status
)));
262 r
= ures_getByKey(r
, key
, r
, &status
);
263 U_DEBUG_TZ_MSG(("loadRule(%s) -> item [%s]\n", key
, u_errorName(status
)));
268 * Given an ID, open the appropriate resource for the given time zone.
269 * Dereference aliases if necessary.
271 * @param res resource, which must be ready for use (initialized but not open)
272 * @param ec input-output error code
273 * @return top-level resource bundle
275 static UResourceBundle
* openOlsonResource(const UnicodeString
& id
,
276 UResourceBundle
& res
,
281 id
.extract(0, sizeof(buf
)-1, buf
, sizeof(buf
), "");
283 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
284 U_DEBUG_TZ_MSG(("pre: res sz=%d\n", ures_getSize(&res
)));
285 /* &res = */ getZoneByName(top
, id
, &res
, ec
);
286 // Dereference if this is an alias. Docs say result should be 1
287 // but it is 0 in 2.8 (?).
288 U_DEBUG_TZ_MSG(("Loading zone '%s' (%s, size %d) - %s\n", buf
, ures_getKey((UResourceBundle
*)&res
), ures_getSize(&res
), u_errorName(ec
)));
289 if (ures_getSize(&res
) <= 1 && getOlsonMeta(top
)) {
290 int32_t deref
= ures_getInt(&res
, &ec
) + 0;
291 U_DEBUG_TZ_MSG(("getInt: %s - type is %d\n", u_errorName(ec
), ures_getType(&res
)));
292 UResourceBundle
*ares
= ures_getByKey(top
, kZONES
, NULL
, &ec
); // dereference Zones section
293 ures_getByIndex(ares
, deref
, &res
, &ec
);
295 U_DEBUG_TZ_MSG(("alias to #%d (%s) - %s\n", deref
, "??", u_errorName(ec
)));
297 U_DEBUG_TZ_MSG(("not an alias - size %d\n", ures_getSize(&res
)));
299 U_DEBUG_TZ_MSG(("%s - final status is %s\n", buf
, u_errorName(ec
)));
303 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
306 * Load all the ids from the "zoneinfo" resource bundle into a static
307 * array that we hang onto. This is _only_ used to implement the
308 * deprecated createAvailableIDs() API.
310 static UBool
loadOlsonIDs() {
311 if (OLSON_IDS
!= 0) {
315 UErrorCode ec
= U_ZERO_ERROR
;
316 UnicodeString
* ids
= 0;
318 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
319 UResourceBundle
*nres
= ures_getByKey(top
, kNAMES
, NULL
, &ec
); // dereference Names section
323 count
= ures_getSize(nres
);
324 ids
= new UnicodeString
[(count
> 0) ? count
: 1];
325 for (int32_t i
=0; i
<count
; ++i
) {
327 const UChar
* id
= ures_getStringByIndex(nres
, i
, &idLen
, &ec
);
328 ids
[i
].fastCopyFrom(UnicodeString(TRUE
, id
, idLen
));
342 // Keep mutexed operations as short as possible by doing all
343 // computations first, then doing pointer copies within the mutex.
345 if (OLSON_IDS
== 0) {
348 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
352 // If another thread initialized the statics first, then delete
360 // -------------------------------------
362 const TimeZone
* U_EXPORT2
363 TimeZone::getGMT(void)
365 umtx_init(&LOCK
); /* This is here to prevent race conditions. */
367 // Initialize _GMT independently of other static data; it should
368 // be valid even if we can't load the time zone UDataMemory.
370 _GMT
= new SimpleTimeZone(0, UnicodeString(GMT_ID
, GMT_ID_LENGTH
));
371 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
376 // *****************************************************************************
378 // *****************************************************************************
380 UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(TimeZone
)
387 // -------------------------------------
389 TimeZone::TimeZone(const UnicodeString
&id
)
394 // -------------------------------------
396 TimeZone::~TimeZone()
400 // -------------------------------------
402 TimeZone::TimeZone(const TimeZone
&source
)
403 : UObject(source
), fID(source
.fID
)
407 // -------------------------------------
410 TimeZone::operator=(const TimeZone
&right
)
412 if (this != &right
) fID
= right
.fID
;
416 // -------------------------------------
419 TimeZone::operator==(const TimeZone
& that
) const
421 return getDynamicClassID() == that
.getDynamicClassID() &&
425 // -------------------------------------
428 TimeZone::createTimeZone(const UnicodeString
& ID
)
430 /* We first try to lookup the zone ID in our system list. If this
431 * fails, we try to parse it as a custom string GMT[+-]hh:mm. If
432 * all else fails, we return GMT, which is probably not what the
433 * user wants, but at least is a functioning TimeZone object.
435 * We cannot return NULL, because that would break compatibility
438 TimeZone
* result
= createSystemTimeZone(ID
);
441 U_DEBUG_TZ_MSG(("failed to load system time zone with id - falling to custom"));
442 result
= createCustomTimeZone(ID
);
445 U_DEBUG_TZ_MSG(("failed to load time zone with id - falling to GMT"));
446 result
= getGMT()->clone();
452 * Lookup the given name in our system zone table. If found,
453 * instantiate a new zone of that name and return it. If not
457 TimeZone::createSystemTimeZone(const UnicodeString
& id
) {
459 UErrorCode ec
= U_ZERO_ERROR
;
461 ures_initStackObject(&res
);
462 U_DEBUG_TZ_MSG(("pre-err=%s\n", u_errorName(ec
)));
463 UResourceBundle
*top
= openOlsonResource(id
, res
, ec
);
464 U_DEBUG_TZ_MSG(("post-err=%s\n", u_errorName(ec
)));
466 z
= new OlsonTimeZone(top
, &res
, ec
);
470 U_DEBUG_TZ_MSG(("cstz: olson time zone failed to initialize - err %s\n", u_errorName(ec
)));
476 U_DEBUG_TZ_MSG(("cstz: failed to create, err %s\n", u_errorName(ec
)));
483 // -------------------------------------
486 * Initialize DEFAULT_ZONE from the system default time zone. The
487 * caller should confirm that DEFAULT_ZONE is NULL before calling.
488 * Upon return, DEFAULT_ZONE will not be NULL, unless operator new()
491 * Must be called OUTSIDE mutex.
494 TimeZone::initDefault()
496 // We access system timezone data through TPlatformUtilities,
497 // including tzset(), timezone, and tzname[].
498 int32_t rawOffset
= 0;
501 // First, try to create a system timezone, based
502 // on the string ID in tzname[0].
504 // NOTE: Global mutex here; TimeZone mutex above
505 // mutexed to avoid threading issues in the platform fcns.
506 // Some of the locale/timezone OS functions may not be thread safe,
507 // so the intent is that any setting from anywhere within ICU
508 // happens with the ICU global mutex held.
510 uprv_tzset(); // Initialize tz... system data
512 // Get the timezone ID from the host. This function should do
513 // any required host-specific remapping; e.g., on Windows this
514 // function maps the Date and Time control panel setting to an
516 hostID
= uprv_tzname(0);
518 // Invert sign because UNIX semantics are backwards
519 rawOffset
= uprv_timezone() * -U_MILLIS_PER_SECOND
;
522 TimeZone
* default_zone
= NULL
;
524 /* Make sure that the string is NULL terminated to prevent BoundsChecker/Purify warnings. */
525 UnicodeString
hostStrID(hostID
, -1, US_INV
);
526 hostStrID
.append((UChar
)0);
527 hostStrID
.truncate(hostStrID
.length()-1);
528 default_zone
= createSystemTimeZone(hostStrID
);
530 int32_t hostIDLen
= hostStrID
.length();
531 if (default_zone
!= NULL
&& rawOffset
!= default_zone
->getRawOffset()
532 && (3 <= hostIDLen
&& hostIDLen
<= 4))
534 // Uh oh. This probably wasn't a good id.
535 // It was probably an ambiguous abbreviation
541 // NOTE: As of ICU 2.8, we no longer have an offsets table, since
542 // historical zones can change offset over time. If we add
543 // build-time heuristics to infer the "most frequent" raw offset
544 // of a zone, we can build tables and institute defaults, as done
547 // If we couldn't get the time zone ID from the host, use
548 // the default host timezone offset. Further refinements
549 // to this include querying the host to determine if DST
550 // is in use or not and possibly using the host locale to
551 // select from multiple zones at a the same offset. We
552 // don't do any of this now, but we could easily add this.
553 if (default_zone
== NULL
) {
554 // Use the designated default in the time zone list that has the
555 // appropriate GMT offset, if there is one.
557 const OffsetIndex
* index
= INDEX_BY_OFFSET
;
560 if (index
->gmtOffset
> rawOffset
) {
561 // Went past our desired offset; no match found
564 if (index
->gmtOffset
== rawOffset
) {
565 // Found our desired offset
566 default_zone
= createSystemTimeZone(ZONE_IDS
[index
->defaultZone
]);
569 // Compute the position of the next entry. If the delta value
570 // in this entry is zero, then there is no next entry.
571 uint16_t delta
= index
->nextEntryDelta
;
575 index
= (const OffsetIndex
*)((int8_t*)index
+ delta
);
580 // Construct a fixed standard zone with the host's ID
582 if (default_zone
== NULL
) {
583 default_zone
= new SimpleTimeZone(rawOffset
, hostStrID
);
586 // If we _still_ don't have a time zone, use GMT.
587 if (default_zone
== NULL
) {
588 default_zone
= getGMT()->clone();
591 // If DEFAULT_ZONE is still NULL, set it up.
593 if (DEFAULT_ZONE
== NULL
) {
594 DEFAULT_ZONE
= default_zone
;
596 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
603 // -------------------------------------
606 TimeZone::createDefault()
608 umtx_init(&LOCK
); /* This is here to prevent race conditions. */
610 UBool f
= (DEFAULT_ZONE
!= 0);
616 Mutex
lock(&LOCK
); // In case adoptDefault is called
617 return DEFAULT_ZONE
->clone();
620 // -------------------------------------
623 TimeZone::adoptDefault(TimeZone
* zone
)
627 TimeZone
* old
= NULL
;
629 umtx_init(&LOCK
); /* This is here to prevent race conditions. */
636 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE
, timeZone_cleanup
);
639 // -------------------------------------
642 TimeZone::setDefault(const TimeZone
& zone
)
644 adoptDefault(zone
.clone());
647 //----------------------------------------------------------------------
650 * This is the default implementation for subclasses that do not
651 * override this method. This implementation calls through to the
652 * 8-argument getOffset() method after suitable computations, and
653 * correctly adjusts GMT millis to local millis when necessary.
655 void TimeZone::getOffset(UDate date
, UBool local
, int32_t& rawOffset
,
656 int32_t& dstOffset
, UErrorCode
& ec
) const {
661 rawOffset
= getRawOffset();
663 // Convert to local wall millis if necessary
665 date
+= rawOffset
; // now in local standard millis
668 // When local==FALSE, we might have to recompute. This loop is
669 // executed once, unless a recomputation is required; then it is
671 for (int32_t pass
=0; ; ++pass
) {
672 int32_t year
, month
, dom
, dow
;
673 double day
= uprv_floor(date
/ U_MILLIS_PER_DAY
);
674 int32_t millis
= (int32_t) (date
- day
* U_MILLIS_PER_DAY
);
676 Grego::dayToFields(day
, year
, month
, dom
, dow
);
678 dstOffset
= getOffset(GregorianCalendar::AD
, year
, month
, dom
,
679 (uint8_t) dow
, millis
,
680 Grego::monthLength(year
, month
),
683 // Recompute if local==FALSE, dstOffset!=0, and addition of
684 // the dstOffset puts us in a different day.
685 if (pass
!=0 || local
|| dstOffset
==0) {
689 if (uprv_floor(date
/ U_MILLIS_PER_DAY
) == day
) {
695 // -------------------------------------
697 // New available IDs API as of ICU 2.4. Uses StringEnumeration API.
699 class TZEnumeration
: public StringEnumeration
{
702 // Map into to zones. Our results are zone[map[i]] for
703 // i=0..len-1, where zone[i] is the i-th Olson zone. If map==NULL
704 // then our results are zone[i] for i=0..len-1. Len will be zero
705 // iff the zone data could not be loaded.
710 UBool
getID(int32_t i
) {
711 UErrorCode ec
= U_ZERO_ERROR
;
713 const UChar
* id
= NULL
;
714 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
715 top
= ures_getByKey(top
, kNAMES
, top
, &ec
); // dereference Zones section
716 id
= ures_getStringByIndex(top
, i
, &idLen
, &ec
);
721 unistr
.fastCopyFrom(UnicodeString(TRUE
, id
, idLen
));
724 return U_SUCCESS(ec
);
728 TZEnumeration() : map(NULL
), len(0), pos(0) {
729 if (getOlsonMeta()) {
730 len
= OLSON_ZONE_COUNT
;
734 TZEnumeration(int32_t rawOffset
) : map(NULL
), len(0), pos(0) {
735 if (!getOlsonMeta()) {
739 // Allocate more space than we'll need. The end of the array will
741 map
= (int32_t*)uprv_malloc(OLSON_ZONE_COUNT
* sizeof(int32_t));
746 uprv_memset(map
, 0, sizeof(int32_t) * OLSON_ZONE_COUNT
);
749 for (int32_t i
=0; i
<OLSON_ZONE_COUNT
; ++i
) {
751 // This is VERY inefficient.
752 TimeZone
* z
= TimeZone::createTimeZone(unistr
);
753 // Make sure we get back the ID we wanted (if the ID is
754 // invalid we get back GMT).
755 if (z
!= 0 && z
->getID(s
) == unistr
&&
756 z
->getRawOffset() == rawOffset
) {
764 TZEnumeration(const char* country
) : map(NULL
), len(0), pos(0) {
765 if (!getOlsonMeta()) {
769 char key
[] = {0, 0, 0, 0,0, 0, 0,0, 0, 0,0}; // e.g., "US", or "Default" for no country
771 uprv_strncat(key
, country
, 2);
773 uprv_strcpy(key
, kDEFAULT
);
776 UErrorCode ec
= U_ZERO_ERROR
;
777 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
778 top
= ures_getByKey(top
, kREGIONS
, top
, &ec
); // dereference 'Regions' section
781 ures_initStackObject(&res
);
782 ures_getByKey(top
, key
, &res
, &ec
);
783 // The list of zones is a list of integers, from 0..n-1,
784 // where n is the total number of system zones.
785 const int32_t* v
= ures_getIntVector(&res
, &len
, &ec
);
788 map
= (int32_t*)uprv_malloc(sizeof(int32_t) * len
);
790 for (uint16_t i
=0; i
<len
; ++i
) {
791 U_ASSERT(v
[i
] >= 0 && v
[i
] < OLSON_ZONE_COUNT
);
796 U_DEBUG_TZ_MSG(("Failed to load tz for region %s: %s\n", country
, u_errorName(ec
)));
803 TZEnumeration(const TZEnumeration
&other
) : StringEnumeration(), map(NULL
), len(0), pos(0) {
805 if(other
.map
!= NULL
) {
806 map
= (int32_t *)uprv_malloc(other
.len
* sizeof(int32_t));
809 uprv_memcpy(map
, other
.map
, len
* sizeof(int32_t));
819 virtual ~TZEnumeration() {
823 virtual StringEnumeration
*clone() const {
824 return new TZEnumeration(*this);
827 virtual int32_t count(UErrorCode
& status
) const {
828 return U_FAILURE(status
) ? 0 : len
;
831 virtual const UnicodeString
* snext(UErrorCode
& status
) {
832 if (U_SUCCESS(status
) && pos
< len
) {
833 getID((map
== 0) ? pos
: map
[pos
]);
840 virtual void reset(UErrorCode
& /*status*/) {
845 static UClassID U_EXPORT2
getStaticClassID(void);
846 virtual UClassID
getDynamicClassID(void) const;
849 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TZEnumeration
)
851 StringEnumeration
* U_EXPORT2
852 TimeZone::createEnumeration() {
853 return new TZEnumeration();
856 StringEnumeration
* U_EXPORT2
857 TimeZone::createEnumeration(int32_t rawOffset
) {
858 return new TZEnumeration(rawOffset
);
861 StringEnumeration
* U_EXPORT2
862 TimeZone::createEnumeration(const char* country
) {
863 return new TZEnumeration(country
);
866 // -------------------------------------
868 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
870 const UnicodeString
**
871 TimeZone::createAvailableIDs(int32_t rawOffset
, int32_t& numIDs
)
873 // We are creating a new array to existing UnicodeString pointers.
874 // The caller will delete the array when done, but not the pointers
878 if (!loadOlsonIDs()) {
882 // Allocate more space than we'll need. The end of the array will
884 const UnicodeString
** ids
=
885 (const UnicodeString
** )uprv_malloc(OLSON_ZONE_COUNT
* sizeof(UnicodeString
*));
890 uprv_memset(ids
, 0, sizeof(UnicodeString
*) * OLSON_ZONE_COUNT
);
893 for (int32_t i
=0; i
<OLSON_ZONE_COUNT
; ++i
) {
894 // This is VERY inefficient.
895 TimeZone
* z
= TimeZone::createTimeZone(OLSON_IDS
[i
]);
896 // Make sure we get back the ID we wanted (if the ID is
897 // invalid we get back GMT).
898 if (z
!= 0 && z
->getID(s
) == OLSON_IDS
[i
] &&
899 z
->getRawOffset() == rawOffset
) {
900 ids
[numIDs
++] = &OLSON_IDS
[i
]; // [sic]
908 // -------------------------------------
910 const UnicodeString
**
911 TimeZone::createAvailableIDs(const char* country
, int32_t& numIDs
) {
913 // We are creating a new array to existing UnicodeString pointers.
914 // The caller will delete the array when done, but not the pointers
918 if (!loadOlsonIDs()) {
922 char key
[] = { 0, 0, 0,0, 0, 0,0, 0, 0 }; // e.g., "US", or "Default" for non-country zones
924 uprv_strncat(key
, country
, 2);
926 uprv_strcpy(key
, kDEFAULT
);
929 const UnicodeString
** ids
= 0;
931 UErrorCode ec
= U_ZERO_ERROR
;
932 UResourceBundle
*top
= ures_openDirect(0, kZONEINFO
, &ec
);
933 UResourceBundle
*ares
= ures_getByKey(top
, kREGIONS
, NULL
, &ec
); // dereference Regions section
937 ures_initStackObject(&res
);
938 ures_getByKey(ares
, key
, &res
, &ec
);
939 U_DEBUG_TZ_MSG(("caI: on %s, err %s\n", country
, u_errorName(ec
)));
941 /* The list of zones is a list of integers, from 0..n-1,
942 * where n is the total number of system zones. The
943 * numbering corresponds exactly to the ordering of
946 const int32_t* v
= ures_getIntVector(&res
, &numIDs
, &ec
);
947 ids
= (const UnicodeString
**)
948 uprv_malloc(numIDs
* sizeof(UnicodeString
*));
952 for (int32_t i
=0; i
<numIDs
; ++i
) {
953 ids
[i
] = &OLSON_IDS
[v
[i
]]; // [sic]
965 // -------------------------------------
967 const UnicodeString
**
968 TimeZone::createAvailableIDs(int32_t& numIDs
)
970 // We are creating a new array to existing UnicodeString pointers.
971 // The caller will delete the array when done, but not the pointers
974 if (!loadOlsonIDs()) {
978 const UnicodeString
** ids
=
979 (const UnicodeString
** )uprv_malloc(OLSON_ZONE_COUNT
* sizeof(UnicodeString
*));
981 numIDs
= OLSON_ZONE_COUNT
;
982 for (int32_t i
=0; i
<numIDs
; ++i
) {
983 ids
[i
] = &OLSON_IDS
[i
];
992 // ---------------------------------------
995 TimeZone::countEquivalentIDs(const UnicodeString
& id
) {
997 UErrorCode ec
= U_ZERO_ERROR
;
999 ures_initStackObject(&res
);
1000 U_DEBUG_TZ_MSG(("countEquivalentIDs..\n"));
1001 UResourceBundle
*top
= openOlsonResource(id
, res
, ec
);
1002 if (U_SUCCESS(ec
)) {
1003 int32_t size
= ures_getSize(&res
);
1004 U_DEBUG_TZ_MSG(("cEI: success (size %d, key %s)..\n", size
, ures_getKey(&res
)));
1005 if (size
== 4 || size
== 6) {
1007 ures_initStackObject(&r
);
1008 ures_getByIndex(&res
, size
-1, &r
, &ec
);
1009 //result = ures_getSize(&r); // doesn't work
1010 ures_getIntVector(&r
, &result
, &ec
);
1011 U_DEBUG_TZ_MSG(("ceI: result %d, err %s\n", result
, u_errorName(ec
)));
1015 U_DEBUG_TZ_MSG(("cEI: fail, %s\n", u_errorName(ec
)));
1022 // ---------------------------------------
1024 const UnicodeString U_EXPORT2
1025 TimeZone::getEquivalentID(const UnicodeString
& id
, int32_t index
) {
1026 U_DEBUG_TZ_MSG(("gEI(%d)\n", index
));
1027 UnicodeString result
;
1028 UErrorCode ec
= U_ZERO_ERROR
;
1029 UResourceBundle res
;
1030 ures_initStackObject(&res
);
1031 UResourceBundle
*top
= openOlsonResource(id
, res
, ec
);
1033 if (U_SUCCESS(ec
)) {
1034 int32_t size
= ures_getSize(&res
);
1035 if (size
== 4 || size
== 6) {
1037 ures_initStackObject(&r
);
1038 ures_getByIndex(&res
, size
-1, &r
, &ec
);
1039 const int32_t* v
= ures_getIntVector(&r
, &size
, &ec
);
1040 if (index
>= 0 && index
< size
&& getOlsonMeta()) {
1048 UResourceBundle
*ares
= ures_getByKey(top
, kNAMES
, NULL
, &ec
); // dereference Zones section
1049 if (U_SUCCESS(ec
)) {
1051 const UChar
* id
= ures_getStringByIndex(ares
, zone
, &idLen
, &ec
);
1052 result
.fastCopyFrom(UnicodeString(TRUE
, id
, idLen
));
1053 U_DEBUG_TZ_MSG(("gei(%d) -> %d, len%d, %s\n", index
, zone
, result
.length(), u_errorName(ec
)));
1058 #if defined(U_DEBUG_TZ)
1059 if(result
.length() ==0) {
1060 U_DEBUG_TZ_MSG(("equiv [__, #%d] -> 0 (%s)\n", index
, u_errorName(ec
)));
1066 // ---------------------------------------
1070 TimeZone::getDisplayName(UnicodeString
& result
) const
1072 return getDisplayName(FALSE
,LONG
,Locale::getDefault(), result
);
1076 TimeZone::getDisplayName(const Locale
& locale
, UnicodeString
& result
) const
1078 return getDisplayName(FALSE
, LONG
, locale
, result
);
1082 TimeZone::getDisplayName(UBool daylight
, EDisplayType style
, UnicodeString
& result
) const
1084 return getDisplayName(daylight
,style
, Locale::getDefault(), result
);
1086 //--------------------------------------
1088 TimeZone::getDSTSavings()const {
1089 if (useDaylightTime()) {
1094 //---------------------------------------
1096 TimeZone::getDisplayName(UBool daylight
, EDisplayType style
, const Locale
& locale
, UnicodeString
& result
) const
1098 // SRL TODO: cache the SDF, just like java.
1099 UErrorCode status
= U_ZERO_ERROR
;
1102 fID
.extract(0, sizeof(buf
)-1, buf
, sizeof(buf
), "");
1104 SimpleDateFormat
format(style
== LONG
? ZZZZ_STR
: Z_STR
,locale
,status
);
1105 U_DEBUG_TZ_MSG(("getDisplayName(%s)\n", buf
));
1106 if(!U_SUCCESS(status
))
1110 result
.extract(0, sizeof(buf2
)-1, buf2
, sizeof(buf2
), "");
1111 U_DEBUG_TZ_MSG(("getDisplayName(%s) -> %s\n", buf
, buf2
));
1113 return result
.remove();
1116 // Create a new SimpleTimeZone as a stand-in for this zone; the
1117 // stand-in will have no DST, or all DST, but the same ID and offset,
1118 // and hence the same display name.
1119 // We don't cache these because they're small and cheap to create.
1120 UnicodeString tempID
;
1121 SimpleTimeZone
*tz
= NULL
;
1122 if(daylight
&& useDaylightTime()){
1123 // For the pure-DST zone, we use JANUARY and DECEMBER
1124 int savings
= getDSTSavings();
1125 tz
= new SimpleTimeZone(getRawOffset(), getID(tempID
),
1126 UCAL_JANUARY
, 1, 0, 0,
1127 UCAL_FEBRUARY
, 1, 0, 0,
1130 tz
= new SimpleTimeZone(getRawOffset(), getID(tempID
));
1132 format
.applyPattern(style
== LONG
? ZZZZ_STR
: Z_STR
);
1133 Calendar
*myCalendar
= (Calendar
*)format
.getCalendar();
1134 myCalendar
->setTimeZone(*tz
); // copy
1138 FieldPosition
pos(FieldPosition::DONT_CARE
);
1139 return format
.format(UDate(864000000L), result
, pos
); // Must use a valid date here.
1144 * Parse a custom time zone identifier and return a corresponding zone.
1145 * @param id a string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
1147 * @return a newly created SimpleTimeZone with the given offset and
1148 * no Daylight Savings Time, or null if the id cannot be parsed.
1151 TimeZone::createCustomTimeZone(const UnicodeString
& id
)
1153 static const int32_t kParseFailed
= -99999;
1155 NumberFormat
* numberFormat
= 0;
1157 UnicodeString idUppercase
= id
;
1158 idUppercase
.toUpper();
1160 if (id
.length() > GMT_ID_LENGTH
&&
1161 idUppercase
.startsWith(GMT_ID
))
1163 ParsePosition
pos(GMT_ID_LENGTH
);
1164 UBool negative
= FALSE
;
1167 if (id
[pos
.getIndex()] == 0x002D /*'-'*/)
1169 else if (id
[pos
.getIndex()] != 0x002B /*'+'*/)
1171 pos
.setIndex(pos
.getIndex() + 1);
1173 UErrorCode success
= U_ZERO_ERROR
;
1174 numberFormat
= NumberFormat::createInstance(success
);
1175 if(U_FAILURE(success
)){
1178 numberFormat
->setParseIntegerOnly(TRUE
);
1181 // Look for either hh:mm, hhmm, or hh
1182 int32_t start
= pos
.getIndex();
1184 Formattable
n(kParseFailed
);
1186 numberFormat
->parse(id
, n
, pos
);
1187 if (pos
.getIndex() == start
) {
1188 delete numberFormat
;
1191 offset
= n
.getLong();
1193 if (pos
.getIndex() < id
.length() &&
1194 id
[pos
.getIndex()] == 0x003A /*':'*/)
1198 pos
.setIndex(pos
.getIndex() + 1);
1199 int32_t oldPos
= pos
.getIndex();
1200 n
.setLong(kParseFailed
);
1201 numberFormat
->parse(id
, n
, pos
);
1202 if (pos
.getIndex() == oldPos
) {
1203 delete numberFormat
;
1206 offset
+= n
.getLong();
1212 // Be strict about interpreting something as hh; it must be
1213 // an offset < 30, and it must be one or two digits. Thus
1214 // 0010 is interpreted as 00:10, but 10 is interpreted as
1216 if (offset
< 30 && (pos
.getIndex() - start
) <= 2)
1217 offset
*= 60; // hh, from 00 to 29; 30 is 00:30
1219 offset
= offset
% 100 + offset
/ 100 * 60; // hhmm
1225 delete numberFormat
;
1226 return new SimpleTimeZone(offset
* 60000, CUSTOM_ID
);
1233 TimeZone::hasSameRules(const TimeZone
& other
) const
1235 return (getRawOffset() == other
.getRawOffset() &&
1236 useDaylightTime() == other
.useDaylightTime());
1241 #endif /* #if !UCONFIG_NO_FORMATTING */