]> git.saurik.com Git - apple/icu.git/blob - icuSources/i18n/timezone.cpp
ICU-8.11.1.tar.gz
[apple/icu.git] / icuSources / i18n / timezone.cpp
1 /*
2 *******************************************************************************
3 * Copyright (C) 1997-2006, International Business Machines Corporation and *
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"
39 #include "unicode/ustring.h"
40
41 #ifdef U_DEBUG_TZ
42 # include <stdio.h>
43 # include "uresimp.h" // for debugging
44
45 static void debug_tz_loc(const char *f, int32_t l)
46 {
47 fprintf(stderr, "%s:%d: ", f, l);
48 }
49
50 static 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 }
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;}
61 #else
62 #define U_DEBUG_TZ_MSG(x)
63 #endif
64
65 #if !UCONFIG_NO_FORMATTING
66
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"
72 #include "gregoimp.h"
73 #include "uresimp.h" // struct UResourceBundle
74 #include "olsontz.h"
75 #include "mutex.h"
76 #include "unicode/udata.h"
77 #include "ucln_in.h"
78 #include "cstring.h"
79 #include "cmemory.h"
80 #include "unicode/strenum.h"
81 #include "uassert.h"
82
83 #define kZONEINFO "zoneinfo"
84 #define kREGIONS "Regions"
85 #define kZONES "Zones"
86 #define kRULES "Rules"
87 #define kNAMES "Names"
88 #define kDEFAULT "Default"
89
90 // Static data and constants
91
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[] =
97 {
98 0x43, 0x75, 0x73, 0x74, 0x6F, 0x6D, 0x00 /* "Custom" */
99 };
100
101 static UMTX LOCK;
102 static TimeZone* DEFAULT_ZONE = NULL;
103 static TimeZone* _GMT = NULL; // cf. TimeZone::GMT
104
105 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
106 static UnicodeString* OLSON_IDS = 0;
107 #endif
108
109 U_CDECL_BEGIN
110 static UBool U_CALLCONV timeZone_cleanup(void)
111 {
112 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
113 delete []OLSON_IDS;
114 OLSON_IDS = 0;
115 #endif
116
117 delete DEFAULT_ZONE;
118 DEFAULT_ZONE = NULL;
119
120 delete _GMT;
121 _GMT = NULL;
122
123 if (LOCK) {
124 umtx_destroy(&LOCK);
125 LOCK = NULL;
126 }
127
128 return TRUE;
129 }
130 U_CDECL_END
131
132 U_NAMESPACE_BEGIN
133
134 /**
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'.
140 */
141 static int32_t OLSON_ZONE_START = -1; // starting index of zones
142 static int32_t OLSON_ZONE_COUNT = 0; // count of zones
143
144 /**
145 * Given a pointer to an open "zoneinfo" resource, load up the Olson
146 * meta-data. Return TRUE if successful.
147 */
148 static 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 */
167 static 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
179 static int32_t findInStringArray(UResourceBundle* array, const UnicodeString& id, UErrorCode &status)
180 {
181 UnicodeString copy;
182 const UChar *u;
183 int32_t len;
184
185 int32_t start = 0;
186 int32_t limit = ures_getSize(array);
187 int32_t mid;
188 int32_t lastMid = INT32_MAX;
189 if(U_FAILURE(status) || (limit < 1)) {
190 return -1;
191 }
192 U_DEBUG_TZ_MSG(("fisa: Looking for %s, between %d and %d\n", U_DEBUG_TZ_STR(UnicodeString(id).getTerminatedBuffer()), start, limit));
193
194 for (;;) {
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. */
198 }
199 lastMid = mid;
200 u = ures_getStringByIndex(array, mid, &len, &status);
201 if (U_FAILURE(status)) {
202 break;
203 }
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);
207 if(r==0) {
208 U_DEBUG_TZ_MSG(("fisa: found at %d\n", mid));
209 return mid;
210 } else if(r<0) {
211 limit = mid;
212 } else {
213 start = mid;
214 }
215 }
216 U_DEBUG_TZ_MSG(("fisa: not found\n"));
217 return -1;
218 }
219
220 /**
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.
226 */
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);
230
231 // search for the string
232 int32_t idx = findInStringArray(tmp, id, status);
233
234 if((idx == -1) && U_SUCCESS(status)) {
235 // not found
236 status = U_MISSING_RESOURCE_ERROR;
237 //ures_close(oldbundle);
238 //oldbundle = NULL;
239 } else {
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)));
245 }
246 ures_close(tmp);
247 if(U_FAILURE(status)) {
248 //ures_close(oldbundle);
249 return NULL;
250 } else {
251 return oldbundle;
252 }
253 }
254
255
256 UResourceBundle* TimeZone::loadRule(const UResourceBundle* top, const UnicodeString& ruleid, UResourceBundle* oldbundle, UErrorCode& status) {
257 char key[64];
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)));
264 return r;
265 }
266
267 /**
268 * Given an ID, open the appropriate resource for the given time zone.
269 * Dereference aliases if necessary.
270 * @param id zone id
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
274 */
275 static UResourceBundle* openOlsonResource(const UnicodeString& id,
276 UResourceBundle& res,
277 UErrorCode& ec)
278 {
279 #if U_DEBUG_TZ
280 char buf[128];
281 id.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
282 #endif
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);
294 ures_close(ares);
295 U_DEBUG_TZ_MSG(("alias to #%d (%s) - %s\n", deref, "??", u_errorName(ec)));
296 } else {
297 U_DEBUG_TZ_MSG(("not an alias - size %d\n", ures_getSize(&res)));
298 }
299 U_DEBUG_TZ_MSG(("%s - final status is %s\n", buf, u_errorName(ec)));
300 return top;
301 }
302
303 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
304
305 /**
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.
309 */
310 static UBool loadOlsonIDs() {
311 if (OLSON_IDS != 0) {
312 return TRUE;
313 }
314
315 UErrorCode ec = U_ZERO_ERROR;
316 UnicodeString* ids = 0;
317 int32_t count = 0;
318 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
319 UResourceBundle *nres = ures_getByKey(top, kNAMES, NULL, &ec); // dereference Names section
320 if (U_SUCCESS(ec)) {
321 getOlsonMeta(top);
322 int32_t start = 0;
323 count = ures_getSize(nres);
324 ids = new UnicodeString[(count > 0) ? count : 1];
325 for (int32_t i=0; i<count; ++i) {
326 int32_t idLen = 0;
327 const UChar* id = ures_getStringByIndex(nres, i, &idLen, &ec);
328 ids[i].fastCopyFrom(UnicodeString(TRUE, id, idLen));
329 if (U_FAILURE(ec)) {
330 break;
331 }
332 }
333 }
334 ures_close(nres);
335 ures_close(top);
336
337 if (U_FAILURE(ec)) {
338 delete[] ids;
339 return FALSE;
340 }
341
342 // Keep mutexed operations as short as possible by doing all
343 // computations first, then doing pointer copies within the mutex.
344 umtx_lock(&LOCK);
345 if (OLSON_IDS == 0) {
346 OLSON_IDS = ids;
347 ids = 0;
348 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
349 }
350 umtx_unlock(&LOCK);
351
352 // If another thread initialized the statics first, then delete
353 // our unused data.
354 delete[] ids;
355 return TRUE;
356 }
357
358 #endif
359
360 // -------------------------------------
361
362 const TimeZone* U_EXPORT2
363 TimeZone::getGMT(void)
364 {
365 umtx_init(&LOCK); /* This is here to prevent race conditions. */
366 Mutex lock(&LOCK);
367 // Initialize _GMT independently of other static data; it should
368 // be valid even if we can't load the time zone UDataMemory.
369 if (_GMT == 0) {
370 _GMT = new SimpleTimeZone(0, UnicodeString(GMT_ID, GMT_ID_LENGTH));
371 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
372 }
373 return _GMT;
374 }
375
376 // *****************************************************************************
377 // class TimeZone
378 // *****************************************************************************
379
380 UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(TimeZone)
381
382 TimeZone::TimeZone()
383 : UObject(), fID()
384 {
385 }
386
387 // -------------------------------------
388
389 TimeZone::TimeZone(const UnicodeString &id)
390 : UObject(), fID(id)
391 {
392 }
393
394 // -------------------------------------
395
396 TimeZone::~TimeZone()
397 {
398 }
399
400 // -------------------------------------
401
402 TimeZone::TimeZone(const TimeZone &source)
403 : UObject(source), fID(source.fID)
404 {
405 }
406
407 // -------------------------------------
408
409 TimeZone &
410 TimeZone::operator=(const TimeZone &right)
411 {
412 if (this != &right) fID = right.fID;
413 return *this;
414 }
415
416 // -------------------------------------
417
418 UBool
419 TimeZone::operator==(const TimeZone& that) const
420 {
421 return getDynamicClassID() == that.getDynamicClassID() &&
422 fID == that.fID;
423 }
424
425 // -------------------------------------
426
427 TimeZone* U_EXPORT2
428 TimeZone::createTimeZone(const UnicodeString& ID)
429 {
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.
434 *
435 * We cannot return NULL, because that would break compatibility
436 * with the JDK.
437 */
438 TimeZone* result = createSystemTimeZone(ID);
439
440 if (result == 0) {
441 U_DEBUG_TZ_MSG(("failed to load system time zone with id - falling to custom"));
442 result = createCustomTimeZone(ID);
443 }
444 if (result == 0) {
445 U_DEBUG_TZ_MSG(("failed to load time zone with id - falling to GMT"));
446 result = getGMT()->clone();
447 }
448 return result;
449 }
450
451 /**
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
454 * found, return 0.
455 */
456 TimeZone*
457 TimeZone::createSystemTimeZone(const UnicodeString& id) {
458 TimeZone* z = 0;
459 UErrorCode ec = U_ZERO_ERROR;
460 UResourceBundle res;
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)));
465 if (U_SUCCESS(ec)) {
466 z = new OlsonTimeZone(top, &res, ec);
467 if (z) {
468 z->setID(id);
469 } else {
470 U_DEBUG_TZ_MSG(("cstz: olson time zone failed to initialize - err %s\n", u_errorName(ec)));
471 }
472 }
473 ures_close(&res);
474 ures_close(top);
475 if (U_FAILURE(ec)) {
476 U_DEBUG_TZ_MSG(("cstz: failed to create, err %s\n", u_errorName(ec)));
477 delete z;
478 z = 0;
479 }
480 return z;
481 }
482
483 // -------------------------------------
484
485 /**
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()
489 * returns NULL.
490 *
491 * Must be called OUTSIDE mutex.
492 */
493 void
494 TimeZone::initDefault()
495 {
496 // We access system timezone data through TPlatformUtilities,
497 // including tzset(), timezone, and tzname[].
498 int32_t rawOffset = 0;
499 const char *hostID;
500
501 // First, try to create a system timezone, based
502 // on the string ID in tzname[0].
503 {
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.
509 Mutex lock;
510 uprv_tzset(); // Initialize tz... system data
511
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
515 // ICU timezone ID.
516 hostID = uprv_tzname(0);
517
518 // Invert sign because UNIX semantics are backwards
519 rawOffset = uprv_timezone() * -U_MILLIS_PER_SECOND;
520 }
521
522 TimeZone* default_zone = NULL;
523
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);
529
530 int32_t hostIDLen = hostStrID.length();
531 if (default_zone != NULL && rawOffset != default_zone->getRawOffset()
532 && (3 <= hostIDLen && hostIDLen <= 4))
533 {
534 // Uh oh. This probably wasn't a good id.
535 // It was probably an ambiguous abbreviation
536 delete default_zone;
537 default_zone = NULL;
538 }
539
540 #if 0
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
545 // in ICU <= 2.6.
546
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.
556
557 const OffsetIndex* index = INDEX_BY_OFFSET;
558
559 for (;;) {
560 if (index->gmtOffset > rawOffset) {
561 // Went past our desired offset; no match found
562 break;
563 }
564 if (index->gmtOffset == rawOffset) {
565 // Found our desired offset
566 default_zone = createSystemTimeZone(ZONE_IDS[index->defaultZone]);
567 break;
568 }
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;
572 if (delta == 0) {
573 break;
574 }
575 index = (const OffsetIndex*)((int8_t*)index + delta);
576 }
577 }
578 #endif
579
580 // Construct a fixed standard zone with the host's ID
581 // and raw offset.
582 if (default_zone == NULL) {
583 default_zone = new SimpleTimeZone(rawOffset, hostStrID);
584 }
585
586 // If we _still_ don't have a time zone, use GMT.
587 if (default_zone == NULL) {
588 default_zone = getGMT()->clone();
589 }
590
591 // If DEFAULT_ZONE is still NULL, set it up.
592 umtx_lock(&LOCK);
593 if (DEFAULT_ZONE == NULL) {
594 DEFAULT_ZONE = default_zone;
595 default_zone = NULL;
596 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
597 }
598 umtx_unlock(&LOCK);
599
600 delete default_zone;
601 }
602
603 // -------------------------------------
604
605 TimeZone* U_EXPORT2
606 TimeZone::createDefault()
607 {
608 umtx_init(&LOCK); /* This is here to prevent race conditions. */
609 umtx_lock(&LOCK);
610 UBool f = (DEFAULT_ZONE != 0);
611 umtx_unlock(&LOCK);
612 if (!f) {
613 initDefault();
614 }
615
616 Mutex lock(&LOCK); // In case adoptDefault is called
617 return DEFAULT_ZONE->clone();
618 }
619
620 // -------------------------------------
621
622 void U_EXPORT2
623 TimeZone::adoptDefault(TimeZone* zone)
624 {
625 if (zone != NULL)
626 {
627 TimeZone* old = NULL;
628
629 umtx_init(&LOCK); /* This is here to prevent race conditions. */
630 umtx_lock(&LOCK);
631 old = DEFAULT_ZONE;
632 DEFAULT_ZONE = zone;
633 umtx_unlock(&LOCK);
634
635 delete old;
636 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
637 }
638 }
639 // -------------------------------------
640
641 void U_EXPORT2
642 TimeZone::setDefault(const TimeZone& zone)
643 {
644 adoptDefault(zone.clone());
645 }
646
647 //----------------------------------------------------------------------
648
649 /**
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.
654 */
655 void TimeZone::getOffset(UDate date, UBool local, int32_t& rawOffset,
656 int32_t& dstOffset, UErrorCode& ec) const {
657 if (U_FAILURE(ec)) {
658 return;
659 }
660
661 rawOffset = getRawOffset();
662
663 // Convert to local wall millis if necessary
664 if (!local) {
665 date += rawOffset; // now in local standard millis
666 }
667
668 // When local==FALSE, we might have to recompute. This loop is
669 // executed once, unless a recomputation is required; then it is
670 // executed twice.
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);
675
676 Grego::dayToFields(day, year, month, dom, dow);
677
678 dstOffset = getOffset(GregorianCalendar::AD, year, month, dom,
679 (uint8_t) dow, millis,
680 Grego::monthLength(year, month),
681 ec) - rawOffset;
682
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) {
686 break;
687 }
688 date += dstOffset;
689 if (uprv_floor(date / U_MILLIS_PER_DAY) == day) {
690 break;
691 }
692 }
693 }
694
695 // -------------------------------------
696
697 // New available IDs API as of ICU 2.4. Uses StringEnumeration API.
698
699 class TZEnumeration : public StringEnumeration {
700 private:
701
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.
706 int32_t* map;
707 int32_t len;
708 int32_t pos;
709
710 UBool getID(int32_t i) {
711 UErrorCode ec = U_ZERO_ERROR;
712 int32_t idLen = 0;
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);
717 if(U_FAILURE(ec)) {
718 unistr.truncate(0);
719 }
720 else {
721 unistr.fastCopyFrom(UnicodeString(TRUE, id, idLen));
722 }
723 ures_close(top);
724 return U_SUCCESS(ec);
725 }
726
727 public:
728 TZEnumeration() : map(NULL), len(0), pos(0) {
729 if (getOlsonMeta()) {
730 len = OLSON_ZONE_COUNT;
731 }
732 }
733
734 TZEnumeration(int32_t rawOffset) : map(NULL), len(0), pos(0) {
735 if (!getOlsonMeta()) {
736 return;
737 }
738
739 // Allocate more space than we'll need. The end of the array will
740 // be blank.
741 map = (int32_t*)uprv_malloc(OLSON_ZONE_COUNT * sizeof(int32_t));
742 if (map == 0) {
743 return;
744 }
745
746 uprv_memset(map, 0, sizeof(int32_t) * OLSON_ZONE_COUNT);
747
748 UnicodeString s;
749 for (int32_t i=0; i<OLSON_ZONE_COUNT; ++i) {
750 if (getID(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) {
757 map[len++] = i;
758 }
759 delete z;
760 }
761 }
762 }
763
764 TZEnumeration(const char* country) : map(NULL), len(0), pos(0) {
765 if (!getOlsonMeta()) {
766 return;
767 }
768
769 char key[] = {0, 0, 0, 0,0, 0, 0,0, 0, 0,0}; // e.g., "US", or "Default" for no country
770 if (country) {
771 uprv_strncat(key, country, 2);
772 } else {
773 uprv_strcpy(key, kDEFAULT);
774 }
775
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
779 if (U_SUCCESS(ec)) {
780 UResourceBundle res;
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);
786 if (U_SUCCESS(ec)) {
787 U_ASSERT(len > 0);
788 map = (int32_t*)uprv_malloc(sizeof(int32_t) * len);
789 if (map != 0) {
790 for (uint16_t i=0; i<len; ++i) {
791 U_ASSERT(v[i] >= 0 && v[i] < OLSON_ZONE_COUNT);
792 map[i] = v[i];
793 }
794 }
795 } else {
796 U_DEBUG_TZ_MSG(("Failed to load tz for region %s: %s\n", country, u_errorName(ec)));
797 }
798 ures_close(&res);
799 }
800 ures_close(top);
801 }
802
803 TZEnumeration(const TZEnumeration &other) : StringEnumeration(), map(NULL), len(0), pos(0) {
804 if(other.len > 0) {
805 if(other.map != NULL) {
806 map = (int32_t *)uprv_malloc(other.len * sizeof(int32_t));
807 if(map != NULL) {
808 len = other.len;
809 uprv_memcpy(map, other.map, len * sizeof(int32_t));
810 pos = other.pos;
811 }
812 } else {
813 len = other.len;
814 pos = other.pos;
815 }
816 }
817 }
818
819 virtual ~TZEnumeration() {
820 uprv_free(map);
821 }
822
823 virtual StringEnumeration *clone() const {
824 return new TZEnumeration(*this);
825 }
826
827 virtual int32_t count(UErrorCode& status) const {
828 return U_FAILURE(status) ? 0 : len;
829 }
830
831 virtual const UnicodeString* snext(UErrorCode& status) {
832 if (U_SUCCESS(status) && pos < len) {
833 getID((map == 0) ? pos : map[pos]);
834 ++pos;
835 return &unistr;
836 }
837 return 0;
838 }
839
840 virtual void reset(UErrorCode& /*status*/) {
841 pos = 0;
842 }
843
844 public:
845 static UClassID U_EXPORT2 getStaticClassID(void);
846 virtual UClassID getDynamicClassID(void) const;
847 };
848
849 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TZEnumeration)
850
851 StringEnumeration* U_EXPORT2
852 TimeZone::createEnumeration() {
853 return new TZEnumeration();
854 }
855
856 StringEnumeration* U_EXPORT2
857 TimeZone::createEnumeration(int32_t rawOffset) {
858 return new TZEnumeration(rawOffset);
859 }
860
861 StringEnumeration* U_EXPORT2
862 TimeZone::createEnumeration(const char* country) {
863 return new TZEnumeration(country);
864 }
865
866 // -------------------------------------
867
868 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
869
870 const UnicodeString**
871 TimeZone::createAvailableIDs(int32_t rawOffset, int32_t& numIDs)
872 {
873 // We are creating a new array to existing UnicodeString pointers.
874 // The caller will delete the array when done, but not the pointers
875 // in the array.
876
877 numIDs = 0;
878 if (!loadOlsonIDs()) {
879 return 0;
880 }
881
882 // Allocate more space than we'll need. The end of the array will
883 // be blank.
884 const UnicodeString** ids =
885 (const UnicodeString** )uprv_malloc(OLSON_ZONE_COUNT * sizeof(UnicodeString *));
886 if (ids == 0) {
887 return 0;
888 }
889
890 uprv_memset(ids, 0, sizeof(UnicodeString*) * OLSON_ZONE_COUNT);
891
892 UnicodeString s;
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]
901 }
902 delete z;
903 }
904
905 return ids;
906 }
907
908 // -------------------------------------
909
910 const UnicodeString**
911 TimeZone::createAvailableIDs(const char* country, int32_t& numIDs) {
912
913 // We are creating a new array to existing UnicodeString pointers.
914 // The caller will delete the array when done, but not the pointers
915 // in the array.
916
917 numIDs = 0;
918 if (!loadOlsonIDs()) {
919 return 0;
920 }
921
922 char key[] = { 0, 0, 0,0, 0, 0,0, 0, 0 }; // e.g., "US", or "Default" for non-country zones
923 if (country) {
924 uprv_strncat(key, country, 2);
925 } else {
926 uprv_strcpy(key, kDEFAULT);
927 }
928
929 const UnicodeString** ids = 0;
930
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
934 if (U_SUCCESS(ec)) {
935 getOlsonMeta(top);
936 UResourceBundle res;
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)));
940 if (U_SUCCESS(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
944 * OLSON_IDS.
945 */
946 const int32_t* v = ures_getIntVector(&res, &numIDs, &ec);
947 ids = (const UnicodeString**)
948 uprv_malloc(numIDs * sizeof(UnicodeString*));
949 if (ids == 0) {
950 numIDs = 0;
951 } else {
952 for (int32_t i=0; i<numIDs; ++i) {
953 ids[i] = &OLSON_IDS[v[i]]; // [sic]
954 }
955 }
956 }
957 ures_close(&res);
958 }
959 ures_close(ares);
960 ures_close(top);
961
962 return ids;
963 }
964
965 // -------------------------------------
966
967 const UnicodeString**
968 TimeZone::createAvailableIDs(int32_t& numIDs)
969 {
970 // We are creating a new array to existing UnicodeString pointers.
971 // The caller will delete the array when done, but not the pointers
972 // in the array.
973 numIDs = 0;
974 if (!loadOlsonIDs()) {
975 return 0;
976 }
977
978 const UnicodeString** ids =
979 (const UnicodeString** )uprv_malloc(OLSON_ZONE_COUNT * sizeof(UnicodeString *));
980 if (ids != 0) {
981 numIDs = OLSON_ZONE_COUNT;
982 for (int32_t i=0; i<numIDs; ++i) {
983 ids[i] = &OLSON_IDS[i];
984 }
985 }
986
987 return ids;
988 }
989
990 #endif
991
992 // ---------------------------------------
993
994 int32_t U_EXPORT2
995 TimeZone::countEquivalentIDs(const UnicodeString& id) {
996 int32_t result = 0;
997 UErrorCode ec = U_ZERO_ERROR;
998 UResourceBundle res;
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) {
1006 UResourceBundle r;
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)));
1012 ures_close(&r);
1013 }
1014 } else {
1015 U_DEBUG_TZ_MSG(("cEI: fail, %s\n", u_errorName(ec)));
1016 }
1017 ures_close(&res);
1018 ures_close(top);
1019 return result;
1020 }
1021
1022 // ---------------------------------------
1023
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);
1032 int32_t zone = -1;
1033 if (U_SUCCESS(ec)) {
1034 int32_t size = ures_getSize(&res);
1035 if (size == 4 || size == 6) {
1036 UResourceBundle r;
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()) {
1041 zone = v[index];
1042 }
1043 ures_close(&r);
1044 }
1045 }
1046 ures_close(&res);
1047 if (zone >= 0) {
1048 UResourceBundle *ares = ures_getByKey(top, kNAMES, NULL, &ec); // dereference Zones section
1049 if (U_SUCCESS(ec)) {
1050 int32_t idLen = 0;
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)));
1054 }
1055 ures_close(ares);
1056 }
1057 ures_close(top);
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)));
1061 }
1062 #endif
1063 return result;
1064 }
1065
1066 // ---------------------------------------
1067
1068
1069 UnicodeString&
1070 TimeZone::getDisplayName(UnicodeString& result) const
1071 {
1072 return getDisplayName(FALSE,LONG,Locale::getDefault(), result);
1073 }
1074
1075 UnicodeString&
1076 TimeZone::getDisplayName(const Locale& locale, UnicodeString& result) const
1077 {
1078 return getDisplayName(FALSE, LONG, locale, result);
1079 }
1080
1081 UnicodeString&
1082 TimeZone::getDisplayName(UBool daylight, EDisplayType style, UnicodeString& result) const
1083 {
1084 return getDisplayName(daylight,style, Locale::getDefault(), result);
1085 }
1086 //--------------------------------------
1087 int32_t
1088 TimeZone::getDSTSavings()const {
1089 if (useDaylightTime()) {
1090 return 3600000;
1091 }
1092 return 0;
1093 }
1094 //---------------------------------------
1095 UnicodeString&
1096 TimeZone::getDisplayName(UBool daylight, EDisplayType style, const Locale& locale, UnicodeString& result) const
1097 {
1098 // SRL TODO: cache the SDF, just like java.
1099 UErrorCode status = U_ZERO_ERROR;
1100 #ifdef U_DEBUG_TZ
1101 char buf[128];
1102 fID.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
1103 #endif
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))
1107 {
1108 #ifdef U_DEBUG_TZ
1109 char buf2[128];
1110 result.extract(0, sizeof(buf2)-1, buf2, sizeof(buf2), "");
1111 U_DEBUG_TZ_MSG(("getDisplayName(%s) -> %s\n", buf, buf2));
1112 #endif
1113 return result.remove();
1114 }
1115
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,
1128 savings, status);
1129 }else{
1130 tz = new SimpleTimeZone(getRawOffset(), getID(tempID));
1131 }
1132 format.applyPattern(style == LONG ? ZZZZ_STR : Z_STR);
1133 Calendar *myCalendar = (Calendar*)format.getCalendar();
1134 myCalendar->setTimeZone(*tz); // copy
1135
1136 delete tz;
1137
1138 FieldPosition pos(FieldPosition::DONT_CARE);
1139 return format.format(UDate(864000000L), result, pos); // Must use a valid date here.
1140 }
1141
1142
1143 /**
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
1146 * GMT[+-]hh.
1147 * @return a newly created SimpleTimeZone with the given offset and
1148 * no Daylight Savings Time, or null if the id cannot be parsed.
1149 */
1150 TimeZone*
1151 TimeZone::createCustomTimeZone(const UnicodeString& id)
1152 {
1153 static const int32_t kParseFailed = -99999;
1154
1155 NumberFormat* numberFormat = 0;
1156
1157 UnicodeString idUppercase = id;
1158 idUppercase.toUpper();
1159
1160 if (id.length() > GMT_ID_LENGTH &&
1161 idUppercase.startsWith(GMT_ID))
1162 {
1163 ParsePosition pos(GMT_ID_LENGTH);
1164 UBool negative = FALSE;
1165 int32_t offset;
1166
1167 if (id[pos.getIndex()] == 0x002D /*'-'*/)
1168 negative = TRUE;
1169 else if (id[pos.getIndex()] != 0x002B /*'+'*/)
1170 return 0;
1171 pos.setIndex(pos.getIndex() + 1);
1172
1173 UErrorCode success = U_ZERO_ERROR;
1174 numberFormat = NumberFormat::createInstance(success);
1175 if(U_FAILURE(success)){
1176 return NULL;
1177 }
1178 numberFormat->setParseIntegerOnly(TRUE);
1179
1180
1181 // Look for either hh:mm, hhmm, or hh
1182 int32_t start = pos.getIndex();
1183
1184 Formattable n(kParseFailed);
1185
1186 numberFormat->parse(id, n, pos);
1187 if (pos.getIndex() == start) {
1188 delete numberFormat;
1189 return 0;
1190 }
1191 offset = n.getLong();
1192
1193 if (pos.getIndex() < id.length() &&
1194 id[pos.getIndex()] == 0x003A /*':'*/)
1195 {
1196 // hh:mm
1197 offset *= 60;
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;
1204 return 0;
1205 }
1206 offset += n.getLong();
1207 }
1208 else
1209 {
1210 // hhmm or hh
1211
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
1215 // 10:00.
1216 if (offset < 30 && (pos.getIndex() - start) <= 2)
1217 offset *= 60; // hh, from 00 to 29; 30 is 00:30
1218 else
1219 offset = offset % 100 + offset / 100 * 60; // hhmm
1220 }
1221
1222 if(negative)
1223 offset = -offset;
1224
1225 delete numberFormat;
1226 return new SimpleTimeZone(offset * 60000, CUSTOM_ID);
1227 }
1228 return 0;
1229 }
1230
1231
1232 UBool
1233 TimeZone::hasSameRules(const TimeZone& other) const
1234 {
1235 return (getRawOffset() == other.getRawOffset() &&
1236 useDaylightTime() == other.useDaylightTime());
1237 }
1238
1239 U_NAMESPACE_END
1240
1241 #endif /* #if !UCONFIG_NO_FORMATTING */
1242
1243 //eof