2 *******************************************************************************
3 * Copyright (C) 1997-2013, 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 "utypeinfo.h" // for 'typeid' to work
40 #include "unicode/utypes.h"
41 #include "unicode/ustring.h"
47 # include "uresimp.h" // for debugging
49 static void debug_tz_loc(const char *f, int32_t l)
51 fprintf(stderr, "%s:%d: ", f, l);
54 static void debug_tz_msg(const char *pat, ...)
58 vfprintf(stderr, pat, ap);
61 static char gStrBuf[256];
62 #define U_DEBUG_TZ_STR(x) u_austrncpy(gStrBuf,x,sizeof(gStrBuf)-1)
63 // must use double parens, i.e.: U_DEBUG_TZ_MSG(("four is: %d",4));
64 #define U_DEBUG_TZ_MSG(x) {debug_tz_loc(__FILE__,__LINE__);debug_tz_msg x;}
66 #define U_DEBUG_TZ_MSG(x)
69 #if !UCONFIG_NO_FORMATTING
71 #include "unicode/simpletz.h"
72 #include "unicode/calendar.h"
73 #include "unicode/gregocal.h"
74 #include "unicode/ures.h"
75 #include "unicode/tzfmt.h"
76 #include "unicode/numfmt.h"
78 #include "uresimp.h" // struct UResourceBundle
81 #include "unicode/udata.h"
85 #include "unicode/strenum.h"
89 #define kZONEINFO "zoneinfo64"
90 #define kREGIONS "Regions"
91 #define kZONES "Zones"
92 #define kRULES "Rules"
93 #define kNAMES "Names"
94 #define kTZVERSION "TZVersion"
95 #define kLINKS "links"
96 #define kMAX_CUSTOM_HOUR 23
97 #define kMAX_CUSTOM_MIN 59
98 #define kMAX_CUSTOM_SEC 59
101 #define ZERO_DIGIT 0x0030
104 // Static data and constants
106 static const UChar WORLD[] = {0x30, 0x30, 0x31, 0x00}; /* "001" */
108 static const UChar GMT_ID[] = {0x47, 0x4D, 0x54, 0x00}; /* "GMT" */
109 static const UChar UNKNOWN_ZONE_ID[] = {0x45, 0x74, 0x63, 0x2F, 0x55, 0x6E, 0x6B, 0x6E, 0x6F, 0x77, 0x6E, 0x00}; /* "Etc/Unknown" */
110 static const int32_t GMT_ID_LENGTH = 3;
111 static const int32_t UNKNOWN_ZONE_ID_LENGTH = 11;
113 static icu::TimeZone* DEFAULT_ZONE = NULL;
114 static icu::UInitOnce gDefaultZoneInitOnce = U_INITONCE_INITIALIZER;
116 static icu::TimeZone* _GMT = NULL;
117 static icu::TimeZone* _UNKNOWN_ZONE = NULL;
118 static icu::UInitOnce gStaticZonesInitOnce = U_INITONCE_INITIALIZER;
120 static char TZDATA_VERSION[16];
121 static icu::UInitOnce gTZDataVersionInitOnce = U_INITONCE_INITIALIZER;
123 static int32_t* MAP_SYSTEM_ZONES = NULL;
124 static int32_t* MAP_CANONICAL_SYSTEM_ZONES = NULL;
125 static int32_t* MAP_CANONICAL_SYSTEM_LOCATION_ZONES = NULL;
127 static int32_t LEN_SYSTEM_ZONES = 0;
128 static int32_t LEN_CANONICAL_SYSTEM_ZONES = 0;
129 static int32_t LEN_CANONICAL_SYSTEM_LOCATION_ZONES = 0;
131 static icu::UInitOnce gSystemZonesInitOnce = U_INITONCE_INITIALIZER;
132 static icu::UInitOnce gCanonicalZonesInitOnce = U_INITONCE_INITIALIZER;
133 static icu::UInitOnce gCanonicalLocationZonesInitOnce = U_INITONCE_INITIALIZER;
136 static UBool U_CALLCONV timeZone_cleanup(void)
141 gDefaultZoneInitOnce.reset();
145 delete _UNKNOWN_ZONE;
146 _UNKNOWN_ZONE = NULL;
147 gStaticZonesInitOnce.reset();
149 uprv_memset(TZDATA_VERSION, 0, sizeof(TZDATA_VERSION));
150 gTZDataVersionInitOnce.reset();
152 LEN_SYSTEM_ZONES = 0;
153 uprv_free(MAP_SYSTEM_ZONES);
154 MAP_SYSTEM_ZONES = 0;
155 gSystemZonesInitOnce.reset();
157 LEN_CANONICAL_SYSTEM_ZONES = 0;
158 uprv_free(MAP_CANONICAL_SYSTEM_ZONES);
159 MAP_CANONICAL_SYSTEM_ZONES = 0;
160 gCanonicalZonesInitOnce.reset();
162 LEN_CANONICAL_SYSTEM_LOCATION_ZONES = 0;
163 uprv_free(MAP_CANONICAL_SYSTEM_LOCATION_ZONES);
164 MAP_CANONICAL_SYSTEM_LOCATION_ZONES = 0;
165 gCanonicalLocationZonesInitOnce.reset();
173 static int32_t findInStringArray(UResourceBundle* array, const UnicodeString& id, UErrorCode &status)
180 int32_t limit = ures_getSize(array);
182 int32_t lastMid = INT32_MAX;
183 if(U_FAILURE(status) || (limit < 1)) {
186 U_DEBUG_TZ_MSG(("fisa: Looking for %s, between %d and %d\n", U_DEBUG_TZ_STR(UnicodeString(id).getTerminatedBuffer()), start, limit));
189 mid = (int32_t)((start + limit) / 2);
190 if (lastMid == mid) { /* Have we moved? */
191 break; /* We haven't moved, and it wasn't found. */
194 u = ures_getStringByIndex(array, mid, &len, &status);
195 if (U_FAILURE(status)) {
198 U_DEBUG_TZ_MSG(("tz: compare to %s, %d .. [%d] .. %d\n", U_DEBUG_TZ_STR(u), start, mid, limit));
199 copy.setTo(TRUE, u, len);
200 int r = id.compare(copy);
202 U_DEBUG_TZ_MSG(("fisa: found at %d\n", mid));
210 U_DEBUG_TZ_MSG(("fisa: not found\n"));
215 * Fetch a specific zone by name. Replaces the getByKey call.
216 * @param top Top timezone resource
217 * @param id Time zone ID
218 * @param oldbundle Bundle for reuse (or NULL). see 'ures_open()'
219 * @return the zone's bundle if found, or undefined if error. Reuses oldbundle.
221 static UResourceBundle* getZoneByName(const UResourceBundle* top, const UnicodeString& id, UResourceBundle *oldbundle, UErrorCode& status) {
222 // load the Rules object
223 UResourceBundle *tmp = ures_getByKey(top, kNAMES, NULL, &status);
225 // search for the string
226 int32_t idx = findInStringArray(tmp, id, status);
228 if((idx == -1) && U_SUCCESS(status)) {
230 status = U_MISSING_RESOURCE_ERROR;
231 //ures_close(oldbundle);
234 U_DEBUG_TZ_MSG(("gzbn: oldbundle= size %d, type %d, %s\n", ures_getSize(tmp), ures_getType(tmp), u_errorName(status)));
235 tmp = ures_getByKey(top, kZONES, tmp, &status); // get Zones object from top
236 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)));
237 oldbundle = ures_getByIndex(tmp, idx, oldbundle, &status); // get nth Zone object
238 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)));
241 if(U_FAILURE(status)) {
242 //ures_close(oldbundle);
250 UResourceBundle* TimeZone::loadRule(const UResourceBundle* top, const UnicodeString& ruleid, UResourceBundle* oldbundle, UErrorCode& status) {
252 ruleid.extract(0, sizeof(key)-1, key, (int32_t)sizeof(key)-1, US_INV);
253 U_DEBUG_TZ_MSG(("loadRule(%s)\n", key));
254 UResourceBundle *r = ures_getByKey(top, kRULES, oldbundle, &status);
255 U_DEBUG_TZ_MSG(("loadRule(%s) -> kRULES [%s]\n", key, u_errorName(status)));
256 r = ures_getByKey(r, key, r, &status);
257 U_DEBUG_TZ_MSG(("loadRule(%s) -> item [%s]\n", key, u_errorName(status)));
262 * Given an ID, open the appropriate resource for the given time zone.
263 * Dereference aliases if necessary.
265 * @param res resource, which must be ready for use (initialized but not open)
266 * @param ec input-output error code
267 * @return top-level resource bundle
269 static UResourceBundle* openOlsonResource(const UnicodeString& id,
270 UResourceBundle& res,
275 id.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
277 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
278 U_DEBUG_TZ_MSG(("pre: res sz=%d\n", ures_getSize(&res)));
279 /* &res = */ getZoneByName(top, id, &res, ec);
280 // Dereference if this is an alias. Docs say result should be 1
281 // but it is 0 in 2.8 (?).
282 U_DEBUG_TZ_MSG(("Loading zone '%s' (%s, size %d) - %s\n", buf, ures_getKey((UResourceBundle*)&res), ures_getSize(&res), u_errorName(ec)));
283 if (ures_getType(&res) == URES_INT) {
284 int32_t deref = ures_getInt(&res, &ec) + 0;
285 U_DEBUG_TZ_MSG(("getInt: %s - type is %d\n", u_errorName(ec), ures_getType(&res)));
286 UResourceBundle *ares = ures_getByKey(top, kZONES, NULL, &ec); // dereference Zones section
287 ures_getByIndex(ares, deref, &res, &ec);
289 U_DEBUG_TZ_MSG(("alias to #%d (%s) - %s\n", deref, "??", u_errorName(ec)));
291 U_DEBUG_TZ_MSG(("not an alias - size %d\n", ures_getSize(&res)));
293 U_DEBUG_TZ_MSG(("%s - final status is %s\n", buf, u_errorName(ec)));
297 // -------------------------------------
301 void U_CALLCONV initStaticTimeZones() {
302 // Initialize _GMT independently of other static data; it should
303 // be valid even if we can't load the time zone UDataMemory.
304 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
305 _UNKNOWN_ZONE = new SimpleTimeZone(0, UnicodeString(TRUE, UNKNOWN_ZONE_ID, UNKNOWN_ZONE_ID_LENGTH));
306 _GMT = new SimpleTimeZone(0, UnicodeString(TRUE, GMT_ID, GMT_ID_LENGTH));
309 } // anonymous namespace
311 const TimeZone& U_EXPORT2
312 TimeZone::getUnknown()
314 umtx_initOnce(gStaticZonesInitOnce, &initStaticTimeZones);
315 return *_UNKNOWN_ZONE;
318 const TimeZone* U_EXPORT2
319 TimeZone::getGMT(void)
321 umtx_initOnce(gStaticZonesInitOnce, &initStaticTimeZones);
325 // *****************************************************************************
327 // *****************************************************************************
329 UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(TimeZone)
336 // -------------------------------------
338 TimeZone::TimeZone(const UnicodeString &id)
343 // -------------------------------------
345 TimeZone::~TimeZone()
349 // -------------------------------------
351 TimeZone::TimeZone(const TimeZone &source)
352 : UObject(source), fID(source.fID)
356 // -------------------------------------
359 TimeZone::operator=(const TimeZone &right)
361 if (this != &right) fID = right.fID;
365 // -------------------------------------
368 TimeZone::operator==(const TimeZone& that) const
370 return typeid(*this) == typeid(that) &&
374 // -------------------------------------
378 createSystemTimeZone(const UnicodeString& id, UErrorCode& ec) {
384 ures_initStackObject(&res);
385 U_DEBUG_TZ_MSG(("pre-err=%s\n", u_errorName(ec)));
386 UResourceBundle *top = openOlsonResource(id, res, ec);
387 U_DEBUG_TZ_MSG(("post-err=%s\n", u_errorName(ec)));
389 z = new OlsonTimeZone(top, &res, id, ec);
391 U_DEBUG_TZ_MSG(("cstz: olson time zone failed to initialize - err %s\n", u_errorName(ec)));
397 U_DEBUG_TZ_MSG(("cstz: failed to create, err %s\n", u_errorName(ec)));
405 * Lookup the given name in our system zone table. If found,
406 * instantiate a new zone of that name and return it. If not
410 createSystemTimeZone(const UnicodeString& id) {
411 UErrorCode ec = U_ZERO_ERROR;
412 return createSystemTimeZone(id, ec);
418 TimeZone::createTimeZone(const UnicodeString& ID)
420 /* We first try to lookup the zone ID in our system list. If this
421 * fails, we try to parse it as a custom string GMT[+-]hh:mm. If
422 * all else fails, we return GMT, which is probably not what the
423 * user wants, but at least is a functioning TimeZone object.
425 * We cannot return NULL, because that would break compatibility
428 TimeZone* result = createSystemTimeZone(ID);
431 U_DEBUG_TZ_MSG(("failed to load system time zone with id - falling to custom"));
432 result = createCustomTimeZone(ID);
435 U_DEBUG_TZ_MSG(("failed to load time zone with id - falling to Etc/Unknown(GMT)"));
436 result = getUnknown().clone();
441 // -------------------------------------
444 * Initialize DEFAULT_ZONE from the system default time zone.
445 * Upon return, DEFAULT_ZONE will not be NULL, unless operator new()
448 static void U_CALLCONV initDefault()
450 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
452 // If setDefault() has already been called we can skip getting the
453 // default zone information from the system.
454 if (DEFAULT_ZONE != NULL) {
458 // We access system timezone data through TPlatformUtilities,
459 // including tzset(), timezone, and tzname[].
460 int32_t rawOffset = 0;
463 // First, try to create a system timezone, based
464 // on the string ID in tzname[0].
466 // NOTE: this code is safely single threaded, being only
467 // run via umtx_initOnce().
469 // Some of the locale/timezone OS functions may not be thread safe,
471 // The operating system might actually use ICU to implement timezones.
472 // So we may have ICU calling ICU here, like on AIX.
473 // There shouldn't be a problem with this; initOnce does not hold a mutex
474 // while the init function is being run.
476 uprv_tzset(); // Initialize tz... system data
478 // Get the timezone ID from the host. This function should do
479 // any required host-specific remapping; e.g., on Windows this
480 // function maps the Date and Time control panel setting to an
482 hostID = uprv_tzname(0);
484 // Invert sign because UNIX semantics are backwards
485 rawOffset = uprv_timezone() * -U_MILLIS_PER_SECOND;
487 TimeZone* default_zone = NULL;
489 /* Make sure that the string is NULL terminated to prevent BoundsChecker/Purify warnings. */
490 UnicodeString hostStrID(hostID, -1, US_INV);
491 hostStrID.append((UChar)0);
492 hostStrID.truncate(hostStrID.length()-1);
493 default_zone = createSystemTimeZone(hostStrID);
495 #if U_PLATFORM_USES_ONLY_WIN32_API
496 // hostID points to a heap-allocated location on Windows.
497 uprv_free(const_cast<char *>(hostID));
500 int32_t hostIDLen = hostStrID.length();
501 if (default_zone != NULL && rawOffset != default_zone->getRawOffset()
502 && (3 <= hostIDLen && hostIDLen <= 4))
504 // Uh oh. This probably wasn't a good id.
505 // It was probably an ambiguous abbreviation
510 // Construct a fixed standard zone with the host's ID
512 if (default_zone == NULL) {
513 default_zone = new SimpleTimeZone(rawOffset, hostStrID);
516 // If we _still_ don't have a time zone, use GMT.
517 if (default_zone == NULL) {
518 const TimeZone* temptz = TimeZone::getGMT();
519 // If we can't use GMT, get out.
520 if (temptz == NULL) {
523 default_zone = temptz->clone();
526 // The only way for DEFAULT_ZONE to be non-null at this point is if the user
527 // made a thread-unsafe call to setDefault() or adoptDefault() in another
528 // thread while this thread was doing something that required getting the default.
529 U_ASSERT(DEFAULT_ZONE == NULL);
531 DEFAULT_ZONE = default_zone;
534 // -------------------------------------
537 TimeZone::createDefault()
539 umtx_initOnce(gDefaultZoneInitOnce, initDefault);
540 return (DEFAULT_ZONE != NULL) ? DEFAULT_ZONE->clone() : NULL;
543 // -------------------------------------
546 TimeZone::adoptDefault(TimeZone* zone)
550 TimeZone *old = DEFAULT_ZONE;
553 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
556 // -------------------------------------
559 TimeZone::setDefault(const TimeZone& zone)
561 adoptDefault(zone.clone());
564 //----------------------------------------------------------------------
567 static void U_CALLCONV initMap(USystemTimeZoneType type, UErrorCode& ec) {
568 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
570 UResourceBundle *res = ures_openDirect(0, kZONEINFO, &ec);
571 res = ures_getByKey(res, kNAMES, res, &ec); // dereference Zones section
573 int32_t size = ures_getSize(res);
574 int32_t *m = (int32_t *)uprv_malloc(size * sizeof(int32_t));
576 ec = U_MEMORY_ALLOCATION_ERROR;
578 int32_t numEntries = 0;
579 for (int32_t i = 0; i < size; i++) {
580 UnicodeString id = ures_getUnicodeStringByIndex(res, i, &ec);
584 if (0 == id.compare(UNKNOWN_ZONE_ID, UNKNOWN_ZONE_ID_LENGTH)) {
585 // exclude Etc/Unknown
588 if (type == UCAL_ZONE_TYPE_CANONICAL || type == UCAL_ZONE_TYPE_CANONICAL_LOCATION) {
589 UnicodeString canonicalID;
590 ZoneMeta::getCanonicalCLDRID(id, canonicalID, ec);
594 if (canonicalID != id) {
599 if (type == UCAL_ZONE_TYPE_CANONICAL_LOCATION) {
600 const UChar *region = TimeZone::getRegion(id, ec);
604 if (u_strcmp(region, WORLD) == 0) {
605 // exclude non-location ("001")
613 m = (int32_t *)uprv_realloc(tmp, numEntries * sizeof(int32_t));
615 // realloc failed.. use the original one even it has unused
621 case UCAL_ZONE_TYPE_ANY:
622 U_ASSERT(MAP_SYSTEM_ZONES == NULL);
623 MAP_SYSTEM_ZONES = m;
624 LEN_SYSTEM_ZONES = numEntries;
626 case UCAL_ZONE_TYPE_CANONICAL:
627 U_ASSERT(MAP_CANONICAL_SYSTEM_ZONES == NULL);
628 MAP_CANONICAL_SYSTEM_ZONES = m;
629 LEN_CANONICAL_SYSTEM_ZONES = numEntries;
631 case UCAL_ZONE_TYPE_CANONICAL_LOCATION:
632 U_ASSERT(MAP_CANONICAL_SYSTEM_LOCATION_ZONES == NULL);
633 MAP_CANONICAL_SYSTEM_LOCATION_ZONES = m;
634 LEN_CANONICAL_SYSTEM_LOCATION_ZONES = numEntries;
645 * This is the default implementation for subclasses that do not
646 * override this method. This implementation calls through to the
647 * 8-argument getOffset() method after suitable computations, and
648 * correctly adjusts GMT millis to local millis when necessary.
650 void TimeZone::getOffset(UDate date, UBool local, int32_t& rawOffset,
651 int32_t& dstOffset, UErrorCode& ec) const {
656 rawOffset = getRawOffset();
658 date += rawOffset; // now in local standard millis
661 // When local == TRUE, date might not be in local standard
662 // millis. getOffset taking 7 parameters used here assume
663 // the given time in day is local standard time.
664 // At STD->DST transition, there is a range of time which
665 // does not exist. When 'date' is in this time range
666 // (and local == TRUE), this method interprets the specified
667 // local time as DST. At DST->STD transition, there is a
668 // range of time which occurs twice. In this case, this
669 // method interprets the specified local time as STD.
670 // To support the behavior above, we need to call getOffset
671 // (with 7 args) twice when local == true and DST is
672 // detected in the initial call.
673 for (int32_t pass=0; ; ++pass) {
674 int32_t year, month, dom, dow;
675 double day = uprv_floor(date / U_MILLIS_PER_DAY);
676 int32_t millis = (int32_t) (date - day * U_MILLIS_PER_DAY);
678 Grego::dayToFields(day, year, month, dom, dow);
680 dstOffset = getOffset(GregorianCalendar::AD, year, month, dom,
681 (uint8_t) dow, millis,
682 Grego::monthLength(year, month),
685 // Recompute if local==TRUE, dstOffset!=0.
686 if (pass!=0 || !local || dstOffset == 0) {
689 // adjust to local standard millis
694 // -------------------------------------
696 // New available IDs API as of ICU 2.4. Uses StringEnumeration API.
698 class TZEnumeration : public StringEnumeration {
701 // Map into to zones. Our results are zone[map[i]] for
702 // i=0..len-1, where zone[i] is the i-th Olson zone. If map==NULL
703 // then our results are zone[i] for i=0..len-1. Len will be zero
704 // if the zone data could not be loaded.
710 TZEnumeration(int32_t* mapData, int32_t mapLen, UBool adoptMapData) : pos(0) {
712 localMap = adoptMapData ? mapData : NULL;
716 UBool getID(int32_t i) {
717 UErrorCode ec = U_ZERO_ERROR;
719 const UChar* id = NULL;
720 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
721 top = ures_getByKey(top, kNAMES, top, &ec); // dereference Zones section
722 id = ures_getStringByIndex(top, i, &idLen, &ec);
727 unistr.fastCopyFrom(UnicodeString(TRUE, id, idLen));
730 return U_SUCCESS(ec);
733 static int32_t* getMap(USystemTimeZoneType type, int32_t& len, UErrorCode& ec) {
740 case UCAL_ZONE_TYPE_ANY:
741 umtx_initOnce(gSystemZonesInitOnce, &initMap, type, ec);
742 m = MAP_SYSTEM_ZONES;
743 len = LEN_SYSTEM_ZONES;
745 case UCAL_ZONE_TYPE_CANONICAL:
746 umtx_initOnce(gCanonicalZonesInitOnce, &initMap, type, ec);
747 m = MAP_CANONICAL_SYSTEM_ZONES;
748 len = LEN_CANONICAL_SYSTEM_ZONES;
750 case UCAL_ZONE_TYPE_CANONICAL_LOCATION:
751 umtx_initOnce(gCanonicalLocationZonesInitOnce, &initMap, type, ec);
752 m = MAP_CANONICAL_SYSTEM_LOCATION_ZONES;
753 len = LEN_CANONICAL_SYSTEM_LOCATION_ZONES;
756 ec = U_ILLEGAL_ARGUMENT_ERROR;
766 #define DEFAULT_FILTERED_MAP_SIZE 8
767 #define MAP_INCREMENT_SIZE 8
769 static TZEnumeration* create(USystemTimeZoneType type, const char* region, const int32_t* rawOffset, UErrorCode& ec) {
775 int32_t *baseMap = getMap(type, baseLen, ec);
781 // If any additional conditions are available,
782 // create instance local map filtered by the conditions.
784 int32_t *filteredMap = NULL;
785 int32_t numEntries = 0;
787 if (region != NULL || rawOffset != NULL) {
788 int32_t filteredMapSize = DEFAULT_FILTERED_MAP_SIZE;
789 filteredMap = (int32_t *)uprv_malloc(filteredMapSize * sizeof(int32_t));
790 if (filteredMap == NULL) {
791 ec = U_MEMORY_ALLOCATION_ERROR;
795 // Walk through the base map
796 UResourceBundle *res = ures_openDirect(0, kZONEINFO, &ec);
797 res = ures_getByKey(res, kNAMES, res, &ec); // dereference Zones section
798 for (int32_t i = 0; i < baseLen; i++) {
799 int32_t zidx = baseMap[i];
800 UnicodeString id = ures_getUnicodeStringByIndex(res, zidx, &ec);
804 if (region != NULL) {
806 char tzregion[4]; // max 3 letters + null term
807 TimeZone::getRegion(id, tzregion, sizeof(tzregion), ec);
811 if (uprv_stricmp(tzregion, region) != 0) {
812 // region does not match
816 if (rawOffset != NULL) {
817 // Filter by raw offset
818 // Note: This is VERY inefficient
819 TimeZone *z = createSystemTimeZone(id, ec);
823 int32_t tzoffset = z->getRawOffset();
826 if (tzoffset != *rawOffset) {
831 if (filteredMapSize <= numEntries) {
832 filteredMapSize += MAP_INCREMENT_SIZE;
833 int32_t *tmp = (int32_t *)uprv_realloc(filteredMap, filteredMapSize * sizeof(int32_t));
835 ec = U_MEMORY_ALLOCATION_ERROR;
842 filteredMap[numEntries++] = zidx;
846 uprv_free(filteredMap);
853 TZEnumeration *result = NULL;
855 // Finally, create a new enumeration instance
856 if (filteredMap == NULL) {
857 result = new TZEnumeration(baseMap, baseLen, FALSE);
859 result = new TZEnumeration(filteredMap, numEntries, TRUE);
862 if (result == NULL) {
863 ec = U_MEMORY_ALLOCATION_ERROR;
867 if (filteredMap != NULL) {
868 uprv_free(filteredMap);
874 TZEnumeration(const TZEnumeration &other) : StringEnumeration(), map(NULL), localMap(NULL), len(0), pos(0) {
875 if (other.localMap != NULL) {
876 localMap = (int32_t *)uprv_malloc(other.len * sizeof(int32_t));
877 if (localMap != NULL) {
879 uprv_memcpy(localMap, other.localMap, len * sizeof(int32_t));
895 virtual ~TZEnumeration();
897 virtual StringEnumeration *clone() const {
898 return new TZEnumeration(*this);
901 virtual int32_t count(UErrorCode& status) const {
902 return U_FAILURE(status) ? 0 : len;
905 virtual const UnicodeString* snext(UErrorCode& status) {
906 if (U_SUCCESS(status) && map != NULL && pos < len) {
914 virtual void reset(UErrorCode& /*status*/) {
919 static UClassID U_EXPORT2 getStaticClassID(void);
920 virtual UClassID getDynamicClassID(void) const;
923 TZEnumeration::~TZEnumeration() {
924 if (localMap != NULL) {
929 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TZEnumeration)
931 StringEnumeration* U_EXPORT2
932 TimeZone::createTimeZoneIDEnumeration(
933 USystemTimeZoneType zoneType,
935 const int32_t* rawOffset,
937 return TZEnumeration::create(zoneType, region, rawOffset, ec);
940 StringEnumeration* U_EXPORT2
941 TimeZone::createEnumeration() {
942 UErrorCode ec = U_ZERO_ERROR;
943 return TZEnumeration::create(UCAL_ZONE_TYPE_ANY, NULL, NULL, ec);
946 StringEnumeration* U_EXPORT2
947 TimeZone::createEnumeration(int32_t rawOffset) {
948 UErrorCode ec = U_ZERO_ERROR;
949 return TZEnumeration::create(UCAL_ZONE_TYPE_ANY, NULL, &rawOffset, ec);
952 StringEnumeration* U_EXPORT2
953 TimeZone::createEnumeration(const char* country) {
954 UErrorCode ec = U_ZERO_ERROR;
955 return TZEnumeration::create(UCAL_ZONE_TYPE_ANY, country, NULL, ec);
958 // ---------------------------------------
961 TimeZone::countEquivalentIDs(const UnicodeString& id) {
963 UErrorCode ec = U_ZERO_ERROR;
965 ures_initStackObject(&res);
966 U_DEBUG_TZ_MSG(("countEquivalentIDs..\n"));
967 UResourceBundle *top = openOlsonResource(id, res, ec);
970 ures_initStackObject(&r);
971 ures_getByKey(&res, kLINKS, &r, &ec);
972 ures_getIntVector(&r, &result, &ec);
980 // ---------------------------------------
982 const UnicodeString U_EXPORT2
983 TimeZone::getEquivalentID(const UnicodeString& id, int32_t index) {
984 U_DEBUG_TZ_MSG(("gEI(%d)\n", index));
985 UnicodeString result;
986 UErrorCode ec = U_ZERO_ERROR;
988 ures_initStackObject(&res);
989 UResourceBundle *top = openOlsonResource(id, res, ec);
993 ures_initStackObject(&r);
995 ures_getByKey(&res, kLINKS, &r, &ec);
996 const int32_t* v = ures_getIntVector(&r, &size, &ec);
998 if (index >= 0 && index < size) {
1006 UResourceBundle *ares = ures_getByKey(top, kNAMES, NULL, &ec); // dereference Zones section
1007 if (U_SUCCESS(ec)) {
1009 const UChar* id = ures_getStringByIndex(ares, zone, &idLen, &ec);
1010 result.fastCopyFrom(UnicodeString(TRUE, id, idLen));
1011 U_DEBUG_TZ_MSG(("gei(%d) -> %d, len%d, %s\n", index, zone, result.length(), u_errorName(ec)));
1016 #if defined(U_DEBUG_TZ)
1017 if(result.length() ==0) {
1018 U_DEBUG_TZ_MSG(("equiv [__, #%d] -> 0 (%s)\n", index, u_errorName(ec)));
1024 // ---------------------------------------
1026 // These methods are used by ZoneMeta class only.
1029 TimeZone::findID(const UnicodeString& id) {
1030 const UChar *result = NULL;
1031 UErrorCode ec = U_ZERO_ERROR;
1032 UResourceBundle *rb = ures_openDirect(NULL, kZONEINFO, &ec);
1034 // resolve zone index by name
1035 UResourceBundle *names = ures_getByKey(rb, kNAMES, NULL, &ec);
1036 int32_t idx = findInStringArray(names, id, ec);
1037 result = ures_getStringByIndex(names, idx, NULL, &ec);
1038 if (U_FAILURE(ec)) {
1048 TimeZone::dereferOlsonLink(const UnicodeString& id) {
1049 const UChar *result = NULL;
1050 UErrorCode ec = U_ZERO_ERROR;
1051 UResourceBundle *rb = ures_openDirect(NULL, kZONEINFO, &ec);
1053 // resolve zone index by name
1054 UResourceBundle *names = ures_getByKey(rb, kNAMES, NULL, &ec);
1055 int32_t idx = findInStringArray(names, id, ec);
1056 result = ures_getStringByIndex(names, idx, NULL, &ec);
1058 // open the zone bundle by index
1059 ures_getByKey(rb, kZONES, rb, &ec);
1060 ures_getByIndex(rb, idx, rb, &ec);
1062 if (U_SUCCESS(ec)) {
1063 if (ures_getType(rb) == URES_INT) {
1064 // this is a link - dereference the link
1065 int32_t deref = ures_getInt(rb, &ec);
1066 const UChar* tmp = ures_getStringByIndex(names, deref, NULL, &ec);
1067 if (U_SUCCESS(ec)) {
1080 TimeZone::getRegion(const UnicodeString& id) {
1081 UErrorCode status = U_ZERO_ERROR;
1082 return getRegion(id, status);
1086 TimeZone::getRegion(const UnicodeString& id, UErrorCode& status) {
1087 if (U_FAILURE(status)) {
1090 const UChar *result = NULL;
1091 UResourceBundle *rb = ures_openDirect(NULL, kZONEINFO, &status);
1093 // resolve zone index by name
1094 UResourceBundle *res = ures_getByKey(rb, kNAMES, NULL, &status);
1095 int32_t idx = findInStringArray(res, id, status);
1097 // get region mapping
1098 ures_getByKey(rb, kREGIONS, res, &status);
1099 const UChar *tmp = ures_getStringByIndex(res, idx, NULL, &status);
1100 if (U_SUCCESS(status)) {
1111 // ---------------------------------------
1113 TimeZone::getRegion(const UnicodeString& id, char *region, int32_t capacity, UErrorCode& status)
1115 int32_t resultLen = 0;
1117 if (U_FAILURE(status)) {
1121 const UChar *uregion = NULL;
1122 // "Etc/Unknown" is not a system zone ID,
1123 // but in the zone data
1124 if (id.compare(UNKNOWN_ZONE_ID, UNKNOWN_ZONE_ID_LENGTH) != 0) {
1125 uregion = getRegion(id);
1127 if (uregion == NULL) {
1128 status = U_ILLEGAL_ARGUMENT_ERROR;
1131 resultLen = u_strlen(uregion);
1132 // A region code is represented by invariant characters
1133 u_UCharsToChars(uregion, region, uprv_min(resultLen, capacity));
1135 if (capacity < resultLen) {
1136 status = U_BUFFER_OVERFLOW_ERROR;
1140 return u_terminateChars(region, capacity, resultLen, &status);
1143 // ---------------------------------------
1147 TimeZone::getDisplayName(UnicodeString& result) const
1149 return getDisplayName(FALSE,LONG,Locale::getDefault(), result);
1153 TimeZone::getDisplayName(const Locale& locale, UnicodeString& result) const
1155 return getDisplayName(FALSE, LONG, locale, result);
1159 TimeZone::getDisplayName(UBool daylight, EDisplayType style, UnicodeString& result) const
1161 return getDisplayName(daylight,style, Locale::getDefault(), result);
1163 //--------------------------------------
1165 TimeZone::getDSTSavings()const {
1166 if (useDaylightTime()) {
1171 //---------------------------------------
1173 TimeZone::getDisplayName(UBool daylight, EDisplayType style, const Locale& locale, UnicodeString& result) const
1175 UErrorCode status = U_ZERO_ERROR;
1176 UDate date = Calendar::getNow();
1177 UTimeZoneFormatTimeType timeType;
1180 if (style == GENERIC_LOCATION || style == LONG_GENERIC || style == SHORT_GENERIC) {
1181 LocalPointer<TimeZoneFormat> tzfmt(TimeZoneFormat::createInstance(locale, status));
1182 if (U_FAILURE(status)) {
1188 case GENERIC_LOCATION:
1189 tzfmt->format(UTZFMT_STYLE_GENERIC_LOCATION, *this, date, result, &timeType);
1192 tzfmt->format(UTZFMT_STYLE_GENERIC_LONG, *this, date, result, &timeType);
1195 tzfmt->format(UTZFMT_STYLE_GENERIC_SHORT, *this, date, result, &timeType);
1200 // Generic format many use Localized GMT as the final fallback.
1201 // When Localized GMT format is used, the result might not be
1202 // appropriate for the requested daylight value.
1203 if ((daylight && timeType == UTZFMT_TIME_TYPE_STANDARD) || (!daylight && timeType == UTZFMT_TIME_TYPE_DAYLIGHT)) {
1204 offset = daylight ? getRawOffset() + getDSTSavings() : getRawOffset();
1205 if (style == SHORT_GENERIC) {
1206 tzfmt->formatOffsetShortLocalizedGMT(offset, result, status);
1208 tzfmt->formatOffsetLocalizedGMT(offset, result, status);
1211 } else if (style == LONG_GMT || style == SHORT_GMT) {
1212 LocalPointer<TimeZoneFormat> tzfmt(TimeZoneFormat::createInstance(locale, status));
1213 if (U_FAILURE(status)) {
1217 offset = daylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
1220 tzfmt->formatOffsetLocalizedGMT(offset, result, status);
1223 tzfmt->formatOffsetISO8601Basic(offset, FALSE, FALSE, FALSE, result, status);
1230 U_ASSERT(style == LONG || style == SHORT || style == SHORT_COMMONLY_USED);
1231 UTimeZoneNameType nameType = UTZNM_UNKNOWN;
1234 nameType = daylight ? UTZNM_LONG_DAYLIGHT : UTZNM_LONG_STANDARD;
1237 case SHORT_COMMONLY_USED:
1238 nameType = daylight ? UTZNM_SHORT_DAYLIGHT : UTZNM_SHORT_STANDARD;
1243 LocalPointer<TimeZoneNames> tznames(TimeZoneNames::createInstance(locale, status));
1244 if (U_FAILURE(status)) {
1248 UnicodeString canonicalID(ZoneMeta::getCanonicalCLDRID(*this));
1249 tznames->getDisplayName(canonicalID, nameType, date, result);
1250 if (result.isEmpty()) {
1251 // Fallback to localized GMT
1252 LocalPointer<TimeZoneFormat> tzfmt(TimeZoneFormat::createInstance(locale, status));
1253 offset = daylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
1254 if (style == LONG) {
1255 tzfmt->formatOffsetLocalizedGMT(offset, result, status);
1257 tzfmt->formatOffsetShortLocalizedGMT(offset, result, status);
1261 if (U_FAILURE(status)) {
1268 * Parse a custom time zone identifier and return a corresponding zone.
1269 * @param id a string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
1271 * @return a newly created SimpleTimeZone with the given offset and
1272 * no Daylight Savings Time, or null if the id cannot be parsed.
1275 TimeZone::createCustomTimeZone(const UnicodeString& id)
1277 int32_t sign, hour, min, sec;
1278 if (parseCustomID(id, sign, hour, min, sec)) {
1279 UnicodeString customID;
1280 formatCustomID(hour, min, sec, (sign < 0), customID);
1281 int32_t offset = sign * ((hour * 60 + min) * 60 + sec) * 1000;
1282 return new SimpleTimeZone(offset, customID);
1288 TimeZone::getCustomID(const UnicodeString& id, UnicodeString& normalized, UErrorCode& status) {
1289 normalized.remove();
1290 if (U_FAILURE(status)) {
1293 int32_t sign, hour, min, sec;
1294 if (parseCustomID(id, sign, hour, min, sec)) {
1295 formatCustomID(hour, min, sec, (sign < 0), normalized);
1301 TimeZone::parseCustomID(const UnicodeString& id, int32_t& sign,
1302 int32_t& hour, int32_t& min, int32_t& sec) {
1303 static const int32_t kParseFailed = -99999;
1305 NumberFormat* numberFormat = 0;
1306 UnicodeString idUppercase = id;
1307 idUppercase.toUpper("");
1309 if (id.length() > GMT_ID_LENGTH &&
1310 idUppercase.startsWith(GMT_ID, GMT_ID_LENGTH))
1312 ParsePosition pos(GMT_ID_LENGTH);
1318 if (id[pos.getIndex()] == MINUS /*'-'*/) {
1320 } else if (id[pos.getIndex()] != PLUS /*'+'*/) {
1323 pos.setIndex(pos.getIndex() + 1);
1325 UErrorCode success = U_ZERO_ERROR;
1326 numberFormat = NumberFormat::createInstance(success);
1327 if(U_FAILURE(success)){
1330 numberFormat->setParseIntegerOnly(TRUE);
1331 //numberFormat->setLenient(TRUE); // TODO: May need to set this, depends on latest timezone parsing
1333 // Look for either hh:mm, hhmm, or hh
1334 int32_t start = pos.getIndex();
1335 Formattable n(kParseFailed);
1336 numberFormat->parse(id, n, pos);
1337 if (pos.getIndex() == start) {
1338 delete numberFormat;
1343 if (pos.getIndex() < id.length()) {
1344 if (pos.getIndex() - start > 2
1345 || id[pos.getIndex()] != COLON) {
1346 delete numberFormat;
1350 pos.setIndex(pos.getIndex() + 1);
1351 int32_t oldPos = pos.getIndex();
1352 n.setLong(kParseFailed);
1353 numberFormat->parse(id, n, pos);
1354 if ((pos.getIndex() - oldPos) != 2) {
1356 delete numberFormat;
1360 if (pos.getIndex() < id.length()) {
1361 if (id[pos.getIndex()] != COLON) {
1362 delete numberFormat;
1366 pos.setIndex(pos.getIndex() + 1);
1367 oldPos = pos.getIndex();
1368 n.setLong(kParseFailed);
1369 numberFormat->parse(id, n, pos);
1370 if (pos.getIndex() != id.length()
1371 || (pos.getIndex() - oldPos) != 2) {
1372 delete numberFormat;
1378 // Supported formats are below -
1387 int32_t length = pos.getIndex() - start;
1388 if (length <= 0 || 6 < length) {
1390 delete numberFormat;
1396 // already set to hour
1406 min = (hour/100) % 100;
1412 delete numberFormat;
1414 if (hour > kMAX_CUSTOM_HOUR || min > kMAX_CUSTOM_MIN || sec > kMAX_CUSTOM_SEC) {
1423 TimeZone::formatCustomID(int32_t hour, int32_t min, int32_t sec,
1424 UBool negative, UnicodeString& id) {
1425 // Create time zone ID - GMT[+|-]hhmm[ss]
1426 id.setTo(GMT_ID, GMT_ID_LENGTH);
1427 if (hour | min | sec) {
1435 id += (UChar)ZERO_DIGIT;
1437 id += (UChar)(ZERO_DIGIT + hour/10);
1439 id += (UChar)(ZERO_DIGIT + hour%10);
1442 id += (UChar)ZERO_DIGIT;
1444 id += (UChar)(ZERO_DIGIT + min/10);
1446 id += (UChar)(ZERO_DIGIT + min%10);
1451 id += (UChar)ZERO_DIGIT;
1453 id += (UChar)(ZERO_DIGIT + sec/10);
1455 id += (UChar)(ZERO_DIGIT + sec%10);
1463 TimeZone::hasSameRules(const TimeZone& other) const
1465 return (getRawOffset() == other.getRawOffset() &&
1466 useDaylightTime() == other.useDaylightTime());
1469 static void U_CALLCONV initTZDataVersion(UErrorCode &status) {
1470 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
1472 UResourceBundle *bundle = ures_openDirect(NULL, kZONEINFO, &status);
1473 const UChar *tzver = ures_getStringByKey(bundle, kTZVERSION, &len, &status);
1475 if (U_SUCCESS(status)) {
1476 if (len >= (int32_t)sizeof(TZDATA_VERSION)) {
1477 // Ensure that there is always space for a trailing nul in TZDATA_VERSION
1478 len = sizeof(TZDATA_VERSION) - 1;
1480 u_UCharsToChars(tzver, TZDATA_VERSION, len);
1487 TimeZone::getTZDataVersion(UErrorCode& status)
1489 umtx_initOnce(gTZDataVersionInitOnce, &initTZDataVersion, status);
1490 return (const char*)TZDATA_VERSION;
1494 TimeZone::getCanonicalID(const UnicodeString& id, UnicodeString& canonicalID, UErrorCode& status)
1496 UBool isSystemID = FALSE;
1497 return getCanonicalID(id, canonicalID, isSystemID, status);
1501 TimeZone::getCanonicalID(const UnicodeString& id, UnicodeString& canonicalID, UBool& isSystemID,
1504 canonicalID.remove();
1506 if (U_FAILURE(status)) {
1509 if (id.compare(UNKNOWN_ZONE_ID, UNKNOWN_ZONE_ID_LENGTH) == 0) {
1510 // special case - Etc/Unknown is a canonical ID, but not system ID
1511 canonicalID.fastCopyFrom(id);
1514 ZoneMeta::getCanonicalCLDRID(id, canonicalID, status);
1515 if (U_SUCCESS(status)) {
1519 status = U_ZERO_ERROR;
1520 getCustomID(id, canonicalID, status);
1526 #ifndef U_HIDE_DRAFT_API
1528 TimeZone::getWindowsID(const UnicodeString& id, UnicodeString& winid, UErrorCode& status) {
1530 if (U_FAILURE(status)) {
1534 // canonicalize the input ID
1535 UnicodeString canonicalID;
1536 UBool isSystemID = FALSE;
1538 getCanonicalID(id, canonicalID, isSystemID, status);
1539 if (U_FAILURE(status) || !isSystemID) {
1540 // mapping data is only applicable to tz database IDs
1544 UResourceBundle *mapTimezones = ures_openDirect(NULL, "windowsZones", &status);
1545 ures_getByKey(mapTimezones, "mapTimezones", mapTimezones, &status);
1547 if (U_FAILURE(status)) {
1551 UResourceBundle *winzone = NULL;
1552 UBool found = FALSE;
1553 while (ures_hasNext(mapTimezones) && !found) {
1554 winzone = ures_getNextResource(mapTimezones, winzone, &status);
1555 if (U_FAILURE(status)) {
1558 if (ures_getType(winzone) != URES_TABLE) {
1561 UResourceBundle *regionalData = NULL;
1562 while (ures_hasNext(winzone) && !found) {
1563 regionalData = ures_getNextResource(winzone, regionalData, &status);
1564 if (U_FAILURE(status)) {
1567 if (ures_getType(regionalData) != URES_STRING) {
1571 const UChar *tzids = ures_getString(regionalData, &len, &status);
1572 if (U_FAILURE(status)) {
1576 const UChar *start = tzids;
1577 UBool hasNext = TRUE;
1579 const UChar *end = u_strchr(start, (UChar)0x20);
1584 if (canonicalID.compare(start, end - start) == 0) {
1585 winid = UnicodeString(ures_getKey(winzone), -1 , US_INV);
1592 ures_close(regionalData);
1594 ures_close(winzone);
1595 ures_close(mapTimezones);
1600 #define MAX_WINDOWS_ID_SIZE 128
1603 TimeZone::getIDForWindowsID(const UnicodeString& winid, const char* region, UnicodeString& id, UErrorCode& status) {
1605 if (U_FAILURE(status)) {
1609 UResourceBundle *zones = ures_openDirect(NULL, "windowsZones", &status);
1610 ures_getByKey(zones, "mapTimezones", zones, &status);
1611 if (U_FAILURE(status)) {
1616 UErrorCode tmperr = U_ZERO_ERROR;
1617 char winidKey[MAX_WINDOWS_ID_SIZE];
1618 int32_t winKeyLen = winid.extract(0, winid.length(), winidKey, sizeof(winidKey) - 1, US_INV);
1620 if (winKeyLen == 0 || winKeyLen >= (int32_t)sizeof(winidKey)) {
1624 winidKey[winKeyLen] = 0;
1626 ures_getByKey(zones, winidKey, zones, &tmperr); // use tmperr, because windows mapping might not
1627 // be avaiable by design
1628 if (U_FAILURE(tmperr)) {
1633 const UChar *tzid = NULL;
1635 UBool gotID = FALSE;
1637 const UChar *tzids = ures_getStringByKey(zones, region, &len, &tmperr); // use tmperr, because
1638 // regional mapping is optional
1639 if (U_SUCCESS(tmperr)) {
1640 // first ID delimited by space is the defasult one
1641 const UChar *end = u_strchr(tzids, (UChar)0x20);
1643 id.setTo(tzids, -1);
1645 id.setTo(tzids, end - tzids);
1652 tzid = ures_getStringByKey(zones, "001", &len, &status); // using status, because "001" must be
1653 // available at this point
1654 if (U_SUCCESS(status)) {
1655 id.setTo(tzid, len);
1662 #endif /* U_HIDE_DRAFT_API */
1667 #endif /* #if !UCONFIG_NO_FORMATTING */