]> git.saurik.com Git - apple/icu.git/blame - icuSources/i18n/timezone.cpp
ICU-6.2.22.tar.gz
[apple/icu.git] / icuSources / i18n / timezone.cpp
CommitLineData
b75a7d8f
A
1/*
2*******************************************************************************
374ca955 3* Copyright (C) 1997-2004, International Business Machines Corporation and *
b75a7d8f
A
4* others. All Rights Reserved. *
5*******************************************************************************
6*
7* File TIMEZONE.CPP
8*
9* Modification History:
10*
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.
22*
23* ISSUES:
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*********************************************************************************/
37
38#include "unicode/utypes.h"
374ca955
A
39#include "unicode/ustring.h"
40
41#ifdef U_DEBUG_TZ
42# include <stdio.h>
43# include "uresimp.h" // for debugging
44
45static void debug_tz_loc(const char *f, int32_t l)
46{
47 fprintf(stderr, "%s:%d: ", f, l);
48}
49
50static void debug_tz_msg(const char *pat, ...)
51{
52 va_list ap;
53 va_start(ap, pat);
54 vfprintf(stderr, pat, ap);
55 fflush(stderr);
56}
57static 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;}
61#else
62#define U_DEBUG_TZ_MSG(x)
63#endif
b75a7d8f
A
64
65#if !UCONFIG_NO_FORMATTING
66
67#include "unicode/simpletz.h"
68#include "unicode/smpdtfmt.h"
69#include "unicode/calendar.h"
374ca955
A
70#include "unicode/gregocal.h"
71#include "unicode/ures.h"
72#include "gregoimp.h"
73#include "uresimp.h" // struct UResourceBundle
74#include "olsontz.h"
b75a7d8f
A
75#include "mutex.h"
76#include "unicode/udata.h"
b75a7d8f
A
77#include "ucln_in.h"
78#include "cstring.h"
79#include "cmemory.h"
80#include "unicode/strenum.h"
81#include "uassert.h"
82
374ca955
A
83#define kZONEINFO "zoneinfo"
84#define kREGIONS "Regions"
85#define kZONES "Zones"
86#define kRULES "Rules"
87#define kNAMES "Names"
88#define kDEFAULT "Default"
b75a7d8f
A
89
90// Static data and constants
91
92static const UChar GMT_ID[] = {0x47, 0x4D, 0x54, 0x00}; /* "GMT" */
374ca955
A
93static const UChar Z_STR[] = {0x7A, 0x00}; /* "z" */
94static const UChar ZZZZ_STR[] = {0x7A, 0x7A, 0x7A, 0x7A, 0x00}; /* "zzzz" */
b75a7d8f
A
95static const int32_t GMT_ID_LENGTH = 3;
96static const UChar CUSTOM_ID[] =
97{
98 0x43, 0x75, 0x73, 0x74, 0x6F, 0x6D, 0x00 /* "Custom" */
99};
100
b75a7d8f
A
101static UMTX LOCK;
102static TimeZone* DEFAULT_ZONE = NULL;
103static TimeZone* _GMT = NULL; // cf. TimeZone::GMT
b75a7d8f 104
374ca955
A
105#ifdef U_USE_TIMEZONE_OBSOLETE_2_8
106static UnicodeString* OLSON_IDS = 0;
107#endif
b75a7d8f 108
374ca955
A
109U_CDECL_BEGIN
110static UBool U_CALLCONV timeZone_cleanup()
111{
112#ifdef U_USE_TIMEZONE_OBSOLETE_2_8
113 delete []OLSON_IDS;
114 OLSON_IDS = 0;
115#endif
b75a7d8f
A
116
117 delete DEFAULT_ZONE;
118 DEFAULT_ZONE = NULL;
119
120 delete _GMT;
121 _GMT = NULL;
122
b75a7d8f
A
123 if (LOCK) {
124 umtx_destroy(&LOCK);
125 LOCK = NULL;
126 }
127
128 return TRUE;
129}
374ca955 130U_CDECL_END
b75a7d8f
A
131
132U_NAMESPACE_BEGIN
133
134/**
374ca955
A
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'.
b75a7d8f 140 */
374ca955
A
141static int32_t OLSON_ZONE_START = -1; // starting index of zones
142static int32_t OLSON_ZONE_COUNT = 0; // count of zones
b75a7d8f 143
374ca955
A
144/**
145 * Given a pointer to an open "zoneinfo" resource, load up the Olson
146 * meta-data. Return TRUE if successful.
147 */
148static UBool getOlsonMeta(const UResourceBundle* top) {
149 if (OLSON_ZONE_START < 0) {
150 UErrorCode ec = U_ZERO_ERROR;
151 UResourceBundle res;
152 ures_initStackObject(&res);
153 ures_getByKey(top, kZONES, &res, &ec);
154 if(U_SUCCESS(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));
158 }
159 ures_close(&res);
160 }
161 return (OLSON_ZONE_START >= 0);
162}
163
164/**
165 * Load up the Olson meta-data. Return TRUE if successful.
166 */
167static UBool getOlsonMeta() {
168 if (OLSON_ZONE_START < 0) {
169 UErrorCode ec = U_ZERO_ERROR;
170 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
171 if (U_SUCCESS(ec)) {
172 getOlsonMeta(top);
173 }
174 ures_close(top);
175 }
176 return (OLSON_ZONE_START >= 0);
177}
178
179static int32_t findInStringArray(UResourceBundle* array, const UnicodeString& id, UErrorCode &status)
180{
181 UnicodeString copy;
182 copy.fastCopyFrom(id);
183 const UChar* buf = copy.getTerminatedBuffer();
184 const UChar* u = NULL;
185
186 int32_t count = ures_getSize(array);
187 int32_t start = 0;
188 int32_t i;
189 int32_t len;
190 int32_t limit = count;
191 if(U_FAILURE(status) || (count < 1)) {
192 return -1;
193 }
194 U_DEBUG_TZ_MSG(("fisa: Looking for %s, between %d and %d\n", U_DEBUG_TZ_STR(buf), start, limit));
195
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));
203 return i;
204 } else if(r<0) {
205 limit = i;
206 } else {
207 start = i;
208 }
209 }
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));
213 return start;
214 }
215 U_DEBUG_TZ_MSG(("fisa: not found\n"));
216 return -1;
217}
218
219/**
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.
225 */
226static 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);
229
230 // search for the string
231 int32_t idx = findInStringArray(tmp, id, status);
232
233 if((idx == -1) && U_SUCCESS(status)) {
234 // not found
235 status = U_MISSING_RESOURCE_ERROR;
236 //ures_close(oldbundle);
237 //oldbundle = NULL;
238 } else {
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)));
b75a7d8f 244 }
374ca955
A
245 ures_close(tmp);
246 if(U_FAILURE(status)) {
247 //ures_close(oldbundle);
248 return NULL;
249 } else {
250 return oldbundle;
251 }
252}
b75a7d8f 253
b75a7d8f 254
374ca955
A
255UResourceBundle* TimeZone::loadRule(const UResourceBundle* top, const UnicodeString& ruleid, UResourceBundle* oldbundle, UErrorCode& status) {
256 char key[64];
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)));
263 return r;
264}
b75a7d8f 265
374ca955
A
266/**
267 * Given an ID, open the appropriate resource for the given time zone.
268 * Dereference aliases if necessary.
269 * @param id zone id
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
273 */
274static UResourceBundle* openOlsonResource(const UnicodeString& id,
275 UResourceBundle& res,
276 UErrorCode& ec)
277{
278#if U_DEBUG_TZ
279 char buf[128];
280 id.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
281#endif
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);
293 ures_close(ares);
294 U_DEBUG_TZ_MSG(("alias to #%d (%s) - %s\n", deref, "??", u_errorName(ec)));
295 } else {
296 U_DEBUG_TZ_MSG(("not an alias - size %d\n", ures_getSize(&res)));
297 }
298 U_DEBUG_TZ_MSG(("%s - final status is %s\n", buf, u_errorName(ec)));
299 return top;
300}
301
302#ifdef U_USE_TIMEZONE_OBSOLETE_2_8
303
304/**
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.
308 */
309static UBool loadOlsonIDs() {
310 if (OLSON_IDS != 0) {
311 return TRUE;
b75a7d8f 312 }
374ca955
A
313
314 UErrorCode ec = U_ZERO_ERROR;
315 UnicodeString* ids = 0;
316 int32_t count = 0;
317 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
318 UResourceBundle *nres = ures_getByKey(top, kNAMES, NULL, &ec); // dereference Names section
319 if (U_SUCCESS(ec)) {
320 getOlsonMeta(top);
321 int32_t start = 0;
322 count = ures_getSize(nres);
323 ids = new UnicodeString[(count > 0) ? count : 1];
324 for (int32_t i=0; i<count; ++i) {
325 int32_t idLen = 0;
326 const UChar* id = ures_getStringByIndex(nres, i, &idLen, &ec);
327 ids[i].fastCopyFrom(UnicodeString(TRUE, id, idLen));
328 if (U_FAILURE(ec)) {
329 break;
330 }
331 }
332 }
333 ures_close(nres);
334 ures_close(top);
335
336 if (U_FAILURE(ec)) {
337 delete[] ids;
338 return FALSE;
b75a7d8f
A
339 }
340
341 // Keep mutexed operations as short as possible by doing all
342 // computations first, then doing pointer copies within the mutex.
343 umtx_lock(&LOCK);
374ca955
A
344 if (OLSON_IDS == 0) {
345 OLSON_IDS = ids;
346 ids = 0;
347 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
b75a7d8f
A
348 }
349 umtx_unlock(&LOCK);
350
351 // If another thread initialized the statics first, then delete
352 // our unused data.
374ca955 353 delete[] ids;
b75a7d8f
A
354 return TRUE;
355}
356
374ca955 357#endif
b75a7d8f
A
358
359// -------------------------------------
360
374ca955 361const TimeZone* U_EXPORT2
b75a7d8f
A
362TimeZone::getGMT(void)
363{
364 umtx_init(&LOCK); /* This is here to prevent race conditions. */
365 Mutex lock(&LOCK);
366 // Initialize _GMT independently of other static data; it should
367 // be valid even if we can't load the time zone UDataMemory.
368 if (_GMT == 0) {
369 _GMT = new SimpleTimeZone(0, UnicodeString(GMT_ID, GMT_ID_LENGTH));
374ca955 370 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
b75a7d8f
A
371 }
372 return _GMT;
373}
374
375// *****************************************************************************
376// class TimeZone
377// *****************************************************************************
378
374ca955
A
379UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(TimeZone)
380
b75a7d8f
A
381TimeZone::TimeZone()
382 : UObject(), fID()
383{
384}
385
386// -------------------------------------
387
388TimeZone::TimeZone(const UnicodeString &id)
389 : UObject(), fID(id)
390{
391}
392
393// -------------------------------------
394
395TimeZone::~TimeZone()
396{
397}
398
399// -------------------------------------
400
401TimeZone::TimeZone(const TimeZone &source)
402 : UObject(source), fID(source.fID)
403{
404}
405
406// -------------------------------------
407
408TimeZone &
409TimeZone::operator=(const TimeZone &right)
410{
411 if (this != &right) fID = right.fID;
412 return *this;
413}
414
415// -------------------------------------
416
417UBool
418TimeZone::operator==(const TimeZone& that) const
419{
420 return getDynamicClassID() == that.getDynamicClassID() &&
421 fID == that.fID;
422}
423
424// -------------------------------------
425
374ca955 426TimeZone* U_EXPORT2
b75a7d8f
A
427TimeZone::createTimeZone(const UnicodeString& ID)
428{
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.
374ca955
A
433 *
434 * We cannot return NULL, because that would break compatibility
435 * with the JDK.
b75a7d8f 436 */
374ca955 437 TimeZone* result = createSystemTimeZone(ID);
b75a7d8f 438
b75a7d8f 439 if (result == 0) {
374ca955 440 U_DEBUG_TZ_MSG(("failed to load system time zone with id - falling to custom"));
b75a7d8f
A
441 result = createCustomTimeZone(ID);
442 }
443 if (result == 0) {
374ca955 444 U_DEBUG_TZ_MSG(("failed to load time zone with id - falling to GMT"));
b75a7d8f
A
445 result = getGMT()->clone();
446 }
447 return result;
448}
449
b75a7d8f
A
450/**
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
453 * found, return 0.
b75a7d8f
A
454 */
455TimeZone*
374ca955
A
456TimeZone::createSystemTimeZone(const UnicodeString& id) {
457 TimeZone* z = 0;
458 UErrorCode ec = U_ZERO_ERROR;
459 UResourceBundle res;
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)));
464 if (U_SUCCESS(ec)) {
465 z = new OlsonTimeZone(top, &res, ec);
466 if (z) {
467 z->setID(id);
468 } else {
469 U_DEBUG_TZ_MSG(("cstz: olson time zone failed to initialize - err %s\n", u_errorName(ec)));
470 }
471 }
472 ures_close(&res);
473 ures_close(top);
474 if (U_FAILURE(ec)) {
475 U_DEBUG_TZ_MSG(("cstz: failed to create, err %s\n", u_errorName(ec)));
476 delete z;
477 z = 0;
b75a7d8f 478 }
374ca955 479 return z;
b75a7d8f
A
480}
481
482// -------------------------------------
483
484/**
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()
488 * returns NULL.
489 *
490 * Must be called OUTSIDE mutex.
491 */
492void
493TimeZone::initDefault()
494{
495 // We access system timezone data through TPlatformUtilities,
496 // including tzset(), timezone, and tzname[].
497 int32_t rawOffset = 0;
498 const char *hostID;
499
500 // First, try to create a system timezone, based
501 // on the string ID in tzname[0].
502 {
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.
508 Mutex lock;
509 uprv_tzset(); // Initialize tz... system data
510
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
514 // ICU timezone ID.
515 hostID = uprv_tzname(0);
516
517 // Invert sign because UNIX semantics are backwards
518 rawOffset = uprv_timezone() * -U_MILLIS_PER_SECOND;
519 }
520
521 TimeZone* default_zone = NULL;
522
374ca955
A
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);
528
529#if 0
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
534 // in ICU <= 2.6.
535
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.
545
546 const OffsetIndex* index = INDEX_BY_OFFSET;
547
548 for (;;) {
549 if (index->gmtOffset > rawOffset) {
550 // Went past our desired offset; no match found
551 break;
552 }
553 if (index->gmtOffset == rawOffset) {
554 // Found our desired offset
555 default_zone = createSystemTimeZone(ZONE_IDS[index->defaultZone]);
556 break;
b75a7d8f 557 }
374ca955
A
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;
561 if (delta == 0) {
562 break;
563 }
564 index = (const OffsetIndex*)((int8_t*)index + delta);
b75a7d8f
A
565 }
566 }
374ca955 567#endif
b75a7d8f 568
374ca955
A
569 // Construct a fixed standard zone with the host's ID
570 // and raw offset.
571 if (default_zone == NULL) {
572 default_zone = new SimpleTimeZone(rawOffset, hostStrID);
573 }
574
575 // If we _still_ don't have a time zone, use GMT.
b75a7d8f
A
576 if (default_zone == NULL) {
577 default_zone = getGMT()->clone();
578 }
579
580 // If DEFAULT_ZONE is still NULL, set it up.
581 umtx_lock(&LOCK);
582 if (DEFAULT_ZONE == NULL) {
583 DEFAULT_ZONE = default_zone;
584 default_zone = NULL;
374ca955 585 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
b75a7d8f
A
586 }
587 umtx_unlock(&LOCK);
588
589 delete default_zone;
590}
591
592// -------------------------------------
593
374ca955 594TimeZone* U_EXPORT2
b75a7d8f
A
595TimeZone::createDefault()
596{
597 umtx_init(&LOCK); /* This is here to prevent race conditions. */
598 umtx_lock(&LOCK);
599 UBool f = (DEFAULT_ZONE != 0);
600 umtx_unlock(&LOCK);
601 if (!f) {
602 initDefault();
603 }
604
605 Mutex lock(&LOCK); // In case adoptDefault is called
606 return DEFAULT_ZONE->clone();
607}
608
609// -------------------------------------
610
374ca955 611void U_EXPORT2
b75a7d8f
A
612TimeZone::adoptDefault(TimeZone* zone)
613{
614 if (zone != NULL)
615 {
616 TimeZone* old = NULL;
617
618 umtx_init(&LOCK); /* This is here to prevent race conditions. */
619 umtx_lock(&LOCK);
620 old = DEFAULT_ZONE;
621 DEFAULT_ZONE = zone;
622 umtx_unlock(&LOCK);
623
624 delete old;
374ca955 625 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
b75a7d8f
A
626 }
627}
628// -------------------------------------
629
374ca955 630void U_EXPORT2
b75a7d8f
A
631TimeZone::setDefault(const TimeZone& zone)
632{
633 adoptDefault(zone.clone());
634}
635
374ca955
A
636//----------------------------------------------------------------------
637
638/**
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.
643 */
644void TimeZone::getOffset(UDate date, UBool local, int32_t& rawOffset,
645 int32_t& dstOffset, UErrorCode& ec) const {
646 if (U_FAILURE(ec)) {
647 return;
648 }
649
650 rawOffset = getRawOffset();
651
652 // Convert to local wall millis if necessary
653 if (!local) {
654 date += rawOffset; // now in local standard millis
655 }
656
657 // When local==FALSE, we might have to recompute. This loop is
658 // executed once, unless a recomputation is required; then it is
659 // executed twice.
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);
664
665 Grego::dayToFields(day, year, month, dom, dow);
666
667 dstOffset = getOffset(GregorianCalendar::AD, year, month, dom,
668 (uint8_t) dow, millis,
669 Grego::monthLength(year, month),
670 ec) - rawOffset;
671
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) {
675 break;
676 }
677 date += dstOffset;
678 if (uprv_floor(date / U_MILLIS_PER_DAY) == day) {
679 break;
680 }
681 }
682}
683
b75a7d8f
A
684// -------------------------------------
685
686// New available IDs API as of ICU 2.4. Uses StringEnumeration API.
687
688class TZEnumeration : public StringEnumeration {
374ca955
A
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.
b75a7d8f
A
693 int32_t* map;
694 int32_t len;
695 int32_t pos;
b75a7d8f
A
696
697public:
374ca955
A
698 TZEnumeration() : map(NULL), len(0), pos(0) {
699 if (getOlsonMeta()) {
700 len = OLSON_ZONE_COUNT;
b75a7d8f
A
701 }
702 }
703
374ca955
A
704 TZEnumeration(int32_t rawOffset) : map(NULL), len(0), pos(0) {
705 if (!getOlsonMeta()) {
706 return;
707 }
b75a7d8f 708
374ca955
A
709 // Allocate more space than we'll need. The end of the array will
710 // be blank.
711 map = (int32_t*)uprv_malloc(OLSON_ZONE_COUNT * sizeof(int32_t));
712 if (map == 0) {
b75a7d8f
A
713 return;
714 }
715
374ca955
A
716 uprv_memset(map, 0, sizeof(int32_t) * OLSON_ZONE_COUNT);
717
718 UnicodeString s;
719 for (int32_t i=0; i<OLSON_ZONE_COUNT; ++i) {
720 if (getID(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) {
727 map[len++] = i;
b75a7d8f 728 }
374ca955 729 delete z;
b75a7d8f 730 }
b75a7d8f
A
731 }
732 }
733
374ca955
A
734 TZEnumeration(const char* country) : map(NULL), len(0), pos(0) {
735 if (!getOlsonMeta()) {
b75a7d8f
A
736 return;
737 }
738
374ca955
A
739 char key[] = {0, 0, 0, 0,0, 0, 0,0, 0, 0,0}; // e.g., "US", or "Default" for no country
740 if (country) {
741 uprv_strncat(key, country, 2);
742 } else {
743 uprv_strcpy(key, kDEFAULT);
b75a7d8f
A
744 }
745
374ca955
A
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
749 if (U_SUCCESS(ec)) {
750 UResourceBundle res;
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);
756 if (U_SUCCESS(ec)) {
757 U_ASSERT(len > 0);
758 map = (int32_t*)uprv_malloc(sizeof(int32_t) * len);
759 if (map != 0) {
b75a7d8f 760 for (uint16_t i=0; i<len; ++i) {
374ca955
A
761 U_ASSERT(v[i] >= 0 && v[i] < OLSON_ZONE_COUNT);
762 map[i] = v[i];
b75a7d8f
A
763 }
764 }
374ca955
A
765 } else {
766 U_DEBUG_TZ_MSG(("Failed to load tz for region %s: %s\n", country, u_errorName(ec)));
b75a7d8f 767 }
374ca955
A
768 ures_close(&res);
769 }
770 ures_close(top);
771 }
772
773 TZEnumeration(const TZEnumeration &other) : StringEnumeration(), map(NULL), len(0), pos(0) {
774 if(other.len > 0) {
775 if(other.map != NULL) {
776 map = (int32_t *)uprv_malloc(other.len * sizeof(int32_t));
777 if(map != NULL) {
778 len = other.len;
779 uprv_memcpy(map, other.map, len * sizeof(int32_t));
780 pos = other.pos;
781 }
782 } else {
783 len = other.len;
784 pos = other.pos;
b75a7d8f 785 }
b75a7d8f
A
786 }
787 }
788
789 virtual ~TZEnumeration() {
790 uprv_free(map);
b75a7d8f
A
791 }
792
374ca955
A
793 virtual StringEnumeration *clone() const {
794 return new TZEnumeration(*this);
b75a7d8f
A
795 }
796
374ca955
A
797 virtual int32_t count(UErrorCode& status) const {
798 return U_FAILURE(status) ? 0 : len;
b75a7d8f
A
799 }
800
374ca955 801 virtual const UnicodeString* snext(UErrorCode& status) {
b75a7d8f 802 if (U_SUCCESS(status) && pos < len) {
374ca955
A
803 getID((map == 0) ? pos : map[pos]);
804 ++pos;
805 return &unistr;
b75a7d8f 806 }
374ca955 807 return 0;
b75a7d8f
A
808 }
809
374ca955 810 virtual void reset(UErrorCode& /*status*/) {
b75a7d8f
A
811 pos = 0;
812 }
813
814private:
b75a7d8f 815
374ca955
A
816 UBool getID(int32_t i) {
817 UErrorCode ec = U_ZERO_ERROR;
818 int32_t idLen = 0;
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);
823 if(U_FAILURE(ec)) {
824 unistr.truncate(0);
825 }
826 else {
827 unistr.fastCopyFrom(UnicodeString(TRUE, id, idLen));
b75a7d8f 828 }
374ca955
A
829 ures_close(top);
830 return U_SUCCESS(ec);
b75a7d8f 831 }
374ca955
A
832
833public:
834 static UClassID U_EXPORT2 getStaticClassID(void);
835 virtual UClassID getDynamicClassID(void) const;
b75a7d8f
A
836};
837
374ca955 838UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TZEnumeration)
b75a7d8f 839
374ca955 840StringEnumeration* U_EXPORT2
b75a7d8f
A
841TimeZone::createEnumeration() {
842 return new TZEnumeration();
843}
844
374ca955 845StringEnumeration* U_EXPORT2
b75a7d8f
A
846TimeZone::createEnumeration(int32_t rawOffset) {
847 return new TZEnumeration(rawOffset);
848}
849
374ca955 850StringEnumeration* U_EXPORT2
b75a7d8f
A
851TimeZone::createEnumeration(const char* country) {
852 return new TZEnumeration(country);
853}
854
855// -------------------------------------
856
374ca955 857#ifdef U_USE_TIMEZONE_OBSOLETE_2_8
b75a7d8f
A
858
859const UnicodeString**
860TimeZone::createAvailableIDs(int32_t rawOffset, int32_t& numIDs)
861{
862 // We are creating a new array to existing UnicodeString pointers.
863 // The caller will delete the array when done, but not the pointers
864 // in the array.
374ca955
A
865
866 numIDs = 0;
867 if (!loadOlsonIDs()) {
b75a7d8f
A
868 return 0;
869 }
870
374ca955
A
871 // Allocate more space than we'll need. The end of the array will
872 // be blank.
873 const UnicodeString** ids =
874 (const UnicodeString** )uprv_malloc(OLSON_ZONE_COUNT * sizeof(UnicodeString *));
875 if (ids == 0) {
876 return 0;
877 }
b75a7d8f 878
374ca955
A
879 uprv_memset(ids, 0, sizeof(UnicodeString*) * OLSON_ZONE_COUNT);
880
881 UnicodeString s;
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]
b75a7d8f 890 }
374ca955 891 delete z;
b75a7d8f
A
892 }
893
374ca955 894 return ids;
b75a7d8f
A
895}
896
897// -------------------------------------
898
899const UnicodeString**
900TimeZone::createAvailableIDs(const char* country, int32_t& numIDs) {
901
902 // We are creating a new array to existing UnicodeString pointers.
903 // The caller will delete the array when done, but not the pointers
904 // in the array.
b75a7d8f 905
374ca955
A
906 numIDs = 0;
907 if (!loadOlsonIDs()) {
908 return 0;
b75a7d8f
A
909 }
910
374ca955
A
911 char key[] = { 0, 0, 0,0, 0, 0,0, 0, 0 }; // e.g., "US", or "Default" for non-country zones
912 if (country) {
913 uprv_strncat(key, country, 2);
914 } else {
915 uprv_strcpy(key, kDEFAULT);
916 }
917
918 const UnicodeString** ids = 0;
919
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
923 if (U_SUCCESS(ec)) {
924 getOlsonMeta(top);
925 UResourceBundle res;
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)));
929 if (U_SUCCESS(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
933 * OLSON_IDS.
934 */
935 const int32_t* v = ures_getIntVector(&res, &numIDs, &ec);
936 ids = (const UnicodeString**)
937 uprv_malloc(numIDs * sizeof(UnicodeString*));
938 if (ids == 0) {
939 numIDs = 0;
940 } else {
941 for (int32_t i=0; i<numIDs; ++i) {
942 ids[i] = &OLSON_IDS[v[i]]; // [sic]
943 }
b75a7d8f 944 }
b75a7d8f 945 }
374ca955 946 ures_close(&res);
b75a7d8f 947 }
374ca955
A
948 ures_close(ares);
949 ures_close(top);
b75a7d8f 950
374ca955 951 return ids;
b75a7d8f
A
952}
953
954// -------------------------------------
955
956const UnicodeString**
957TimeZone::createAvailableIDs(int32_t& numIDs)
958{
959 // We are creating a new array to existing UnicodeString pointers.
960 // The caller will delete the array when done, but not the pointers
961 // in the array.
374ca955
A
962 numIDs = 0;
963 if (!loadOlsonIDs()) {
b75a7d8f
A
964 return 0;
965 }
374ca955
A
966
967 const UnicodeString** ids =
968 (const UnicodeString** )uprv_malloc(OLSON_ZONE_COUNT * sizeof(UnicodeString *));
969 if (ids != 0) {
970 numIDs = OLSON_ZONE_COUNT;
971 for (int32_t i=0; i<numIDs; ++i) {
972 ids[i] = &OLSON_IDS[i];
973 }
b75a7d8f
A
974 }
975
374ca955 976 return ids;
b75a7d8f
A
977}
978
374ca955 979#endif
b75a7d8f
A
980
981// ---------------------------------------
982
374ca955 983int32_t U_EXPORT2
b75a7d8f 984TimeZone::countEquivalentIDs(const UnicodeString& id) {
374ca955
A
985 int32_t result = 0;
986 UErrorCode ec = U_ZERO_ERROR;
987 UResourceBundle res;
988 ures_initStackObject(&res);
989 U_DEBUG_TZ_MSG(("countEquivalentIDs..\n"));
990 UResourceBundle *top = openOlsonResource(id, res, ec);
991 if (U_SUCCESS(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) {
995 UResourceBundle r;
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)));
1001 ures_close(&r);
1002 }
1003 } else {
1004 U_DEBUG_TZ_MSG(("cEI: fail, %s\n", u_errorName(ec)));
b75a7d8f 1005 }
374ca955
A
1006 ures_close(&res);
1007 ures_close(top);
1008 return result;
b75a7d8f
A
1009}
1010
1011// ---------------------------------------
1012
374ca955 1013const UnicodeString U_EXPORT2
b75a7d8f 1014TimeZone::getEquivalentID(const UnicodeString& id, int32_t index) {
374ca955
A
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);
1021 int32_t zone = -1;
1022 if (U_SUCCESS(ec)) {
1023 int32_t size = ures_getSize(&res);
1024 if (size == 4 || size == 6) {
1025 UResourceBundle r;
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()) {
1030 zone = v[index];
b75a7d8f 1031 }
374ca955
A
1032 ures_close(&r);
1033 }
1034 }
1035 ures_close(&res);
1036 if (zone >= 0) {
1037 UResourceBundle *ares = ures_getByKey(top, kNAMES, NULL, &ec); // dereference Zones section
1038 if (U_SUCCESS(ec)) {
1039 int32_t idLen = 0;
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)));
b75a7d8f 1043 }
374ca955
A
1044 ures_close(ares);
1045 }
1046 ures_close(top);
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)));
b75a7d8f 1050 }
374ca955
A
1051#endif
1052 return result;
b75a7d8f
A
1053}
1054
1055// ---------------------------------------
1056
1057
1058UnicodeString&
1059TimeZone::getDisplayName(UnicodeString& result) const
1060{
1061 return getDisplayName(FALSE,LONG,Locale::getDefault(), result);
1062}
1063
1064UnicodeString&
1065TimeZone::getDisplayName(const Locale& locale, UnicodeString& result) const
1066{
1067 return getDisplayName(FALSE, LONG, locale, result);
1068}
1069
1070UnicodeString&
1071TimeZone::getDisplayName(UBool daylight, EDisplayType style, UnicodeString& result) const
1072{
1073 return getDisplayName(daylight,style, Locale::getDefault(), result);
1074}
1075
1076UnicodeString&
1077TimeZone::getDisplayName(UBool daylight, EDisplayType style, const Locale& locale, UnicodeString& result) const
1078{
1079 // SRL TODO: cache the SDF, just like java.
1080 UErrorCode status = U_ZERO_ERROR;
374ca955
A
1081#ifdef U_DEBUG_TZ
1082 char buf[128];
1083 fID.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
1084#endif
1085 SimpleDateFormat format(style == LONG ? ZZZZ_STR : Z_STR,locale,status);
1086 U_DEBUG_TZ_MSG(("getDisplayName(%s)\n", buf));
b75a7d8f
A
1087 if(!U_SUCCESS(status))
1088 {
374ca955
A
1089#ifdef U_DEBUG_TZ
1090 char buf2[128];
1091 result.extract(0, sizeof(buf2)-1, buf2, sizeof(buf2), "");
1092 U_DEBUG_TZ_MSG(("getDisplayName(%s) -> %s\n", buf, buf2));
1093#endif
1094 return result.remove();
b75a7d8f
A
1095 }
1096
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
1104
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));
1109
374ca955 1110 format.applyPattern(style == LONG ? ZZZZ_STR : Z_STR);
b75a7d8f
A
1111 Calendar *myCalendar = (Calendar*)format.getCalendar();
1112 myCalendar->setTimeZone(*tz); // copy
1113
1114 delete tz;
1115
1116 FieldPosition pos(FieldPosition::DONT_CARE);
1117 return format.format(UDate(196262345678.), result, pos); // Must use a valid date here.
1118}
1119
1120
1121/**
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
1124 * GMT[+-]hh.
1125 * @return a newly created SimpleTimeZone with the given offset and
1126 * no Daylight Savings Time, or null if the id cannot be parsed.
1127*/
1128TimeZone*
1129TimeZone::createCustomTimeZone(const UnicodeString& id)
1130{
1131 static const int32_t kParseFailed = -99999;
1132
1133 NumberFormat* numberFormat = 0;
1134
1135 UnicodeString idUppercase = id;
1136 idUppercase.toUpper();
1137
1138 if (id.length() > GMT_ID_LENGTH &&
1139 idUppercase.startsWith(GMT_ID))
1140 {
1141 ParsePosition pos(GMT_ID_LENGTH);
1142 UBool negative = FALSE;
1143 int32_t offset;
1144
1145 if (id[pos.getIndex()] == 0x002D /*'-'*/)
1146 negative = TRUE;
1147 else if (id[pos.getIndex()] != 0x002B /*'+'*/)
1148 return 0;
1149 pos.setIndex(pos.getIndex() + 1);
1150
1151 UErrorCode success = U_ZERO_ERROR;
1152 numberFormat = NumberFormat::createInstance(success);
1153 numberFormat->setParseIntegerOnly(TRUE);
1154
1155
1156 // Look for either hh:mm, hhmm, or hh
1157 int32_t start = pos.getIndex();
1158
1159 Formattable n(kParseFailed);
1160
1161 numberFormat->parse(id, n, pos);
1162 if (pos.getIndex() == start) {
1163 delete numberFormat;
1164 return 0;
1165 }
1166 offset = n.getLong();
1167
1168 if (pos.getIndex() < id.length() &&
1169 id[pos.getIndex()] == 0x003A /*':'*/)
1170 {
1171 // hh:mm
1172 offset *= 60;
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;
1179 return 0;
1180 }
1181 offset += n.getLong();
1182 }
1183 else
1184 {
1185 // hhmm or hh
1186
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
1190 // 10:00.
1191 if (offset < 30 && (pos.getIndex() - start) <= 2)
1192 offset *= 60; // hh, from 00 to 29; 30 is 00:30
1193 else
1194 offset = offset % 100 + offset / 100 * 60; // hhmm
1195 }
1196
1197 if(negative)
1198 offset = -offset;
1199
1200 delete numberFormat;
1201 return new SimpleTimeZone(offset * 60000, CUSTOM_ID);
1202 }
1203 return 0;
1204}
1205
1206
1207UBool
1208TimeZone::hasSameRules(const TimeZone& other) const
1209{
1210 return (getRawOffset() == other.getRawOffset() &&
1211 useDaylightTime() == other.useDaylightTime());
1212}
1213
1214U_NAMESPACE_END
1215
1216#endif /* #if !UCONFIG_NO_FORMATTING */
1217
1218//eof