]> git.saurik.com Git - apple/icu.git/blob - icuSources/i18n/timezone.cpp
ICU-6.2.14.tar.gz
[apple/icu.git] / icuSources / i18n / timezone.cpp
1 /*
2 *******************************************************************************
3 * Copyright (C) 1997-2004, 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()
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 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 */
226 static UResourceBundle* getZoneByName(const UResourceBundle* top, const UnicodeString& id, UResourceBundle *oldbundle, UErrorCode& status) {
227 // load the Rules object
228 UResourceBundle *tmp = ures_getByKey(top, kNAMES, NULL, &status);
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)));
244 }
245 ures_close(tmp);
246 if(U_FAILURE(status)) {
247 //ures_close(oldbundle);
248 return NULL;
249 } else {
250 return oldbundle;
251 }
252 }
253
254
255 UResourceBundle* 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 }
265
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 */
274 static 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 */
309 static UBool loadOlsonIDs() {
310 if (OLSON_IDS != 0) {
311 return TRUE;
312 }
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;
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);
344 if (OLSON_IDS == 0) {
345 OLSON_IDS = ids;
346 ids = 0;
347 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
348 }
349 umtx_unlock(&LOCK);
350
351 // If another thread initialized the statics first, then delete
352 // our unused data.
353 delete[] ids;
354 return TRUE;
355 }
356
357 #endif
358
359 // -------------------------------------
360
361 const TimeZone* U_EXPORT2
362 TimeZone::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));
370 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
371 }
372 return _GMT;
373 }
374
375 // *****************************************************************************
376 // class TimeZone
377 // *****************************************************************************
378
379 UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(TimeZone)
380
381 TimeZone::TimeZone()
382 : UObject(), fID()
383 {
384 }
385
386 // -------------------------------------
387
388 TimeZone::TimeZone(const UnicodeString &id)
389 : UObject(), fID(id)
390 {
391 }
392
393 // -------------------------------------
394
395 TimeZone::~TimeZone()
396 {
397 }
398
399 // -------------------------------------
400
401 TimeZone::TimeZone(const TimeZone &source)
402 : UObject(source), fID(source.fID)
403 {
404 }
405
406 // -------------------------------------
407
408 TimeZone &
409 TimeZone::operator=(const TimeZone &right)
410 {
411 if (this != &right) fID = right.fID;
412 return *this;
413 }
414
415 // -------------------------------------
416
417 UBool
418 TimeZone::operator==(const TimeZone& that) const
419 {
420 return getDynamicClassID() == that.getDynamicClassID() &&
421 fID == that.fID;
422 }
423
424 // -------------------------------------
425
426 TimeZone* U_EXPORT2
427 TimeZone::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.
433 *
434 * We cannot return NULL, because that would break compatibility
435 * with the JDK.
436 */
437 TimeZone* result = createSystemTimeZone(ID);
438
439 if (result == 0) {
440 U_DEBUG_TZ_MSG(("failed to load system time zone with id - falling to custom"));
441 result = createCustomTimeZone(ID);
442 }
443 if (result == 0) {
444 U_DEBUG_TZ_MSG(("failed to load time zone with id - falling to GMT"));
445 result = getGMT()->clone();
446 }
447 return result;
448 }
449
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.
454 */
455 TimeZone*
456 TimeZone::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;
478 }
479 return z;
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 */
492 void
493 TimeZone::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
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;
557 }
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);
565 }
566 }
567 #endif
568
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.
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;
585 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
586 }
587 umtx_unlock(&LOCK);
588
589 delete default_zone;
590 }
591
592 // -------------------------------------
593
594 TimeZone* U_EXPORT2
595 TimeZone::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
611 void U_EXPORT2
612 TimeZone::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;
625 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
626 }
627 }
628 // -------------------------------------
629
630 void U_EXPORT2
631 TimeZone::setDefault(const TimeZone& zone)
632 {
633 adoptDefault(zone.clone());
634 }
635
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 */
644 void 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
684 // -------------------------------------
685
686 // New available IDs API as of ICU 2.4. Uses StringEnumeration API.
687
688 class TZEnumeration : public StringEnumeration {
689 // Map into to zones. Our results are zone[map[i]] for
690 // i=0..len-1, where zone[i] is the i-th Olson zone. If map==NULL
691 // then our results are zone[i] for i=0..len-1. Len will be zero
692 // iff the zone data could not be loaded.
693 int32_t* map;
694 int32_t len;
695 int32_t pos;
696
697 public:
698 TZEnumeration() : map(NULL), len(0), pos(0) {
699 if (getOlsonMeta()) {
700 len = OLSON_ZONE_COUNT;
701 }
702 }
703
704 TZEnumeration(int32_t rawOffset) : map(NULL), len(0), pos(0) {
705 if (!getOlsonMeta()) {
706 return;
707 }
708
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) {
713 return;
714 }
715
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;
728 }
729 delete z;
730 }
731 }
732 }
733
734 TZEnumeration(const char* country) : map(NULL), len(0), pos(0) {
735 if (!getOlsonMeta()) {
736 return;
737 }
738
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);
744 }
745
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) {
760 for (uint16_t i=0; i<len; ++i) {
761 U_ASSERT(v[i] >= 0 && v[i] < OLSON_ZONE_COUNT);
762 map[i] = v[i];
763 }
764 }
765 } else {
766 U_DEBUG_TZ_MSG(("Failed to load tz for region %s: %s\n", country, u_errorName(ec)));
767 }
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;
785 }
786 }
787 }
788
789 virtual ~TZEnumeration() {
790 uprv_free(map);
791 }
792
793 virtual StringEnumeration *clone() const {
794 return new TZEnumeration(*this);
795 }
796
797 virtual int32_t count(UErrorCode& status) const {
798 return U_FAILURE(status) ? 0 : len;
799 }
800
801 virtual const UnicodeString* snext(UErrorCode& status) {
802 if (U_SUCCESS(status) && pos < len) {
803 getID((map == 0) ? pos : map[pos]);
804 ++pos;
805 return &unistr;
806 }
807 return 0;
808 }
809
810 virtual void reset(UErrorCode& /*status*/) {
811 pos = 0;
812 }
813
814 private:
815
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));
828 }
829 ures_close(top);
830 return U_SUCCESS(ec);
831 }
832
833 public:
834 static UClassID U_EXPORT2 getStaticClassID(void);
835 virtual UClassID getDynamicClassID(void) const;
836 };
837
838 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TZEnumeration)
839
840 StringEnumeration* U_EXPORT2
841 TimeZone::createEnumeration() {
842 return new TZEnumeration();
843 }
844
845 StringEnumeration* U_EXPORT2
846 TimeZone::createEnumeration(int32_t rawOffset) {
847 return new TZEnumeration(rawOffset);
848 }
849
850 StringEnumeration* U_EXPORT2
851 TimeZone::createEnumeration(const char* country) {
852 return new TZEnumeration(country);
853 }
854
855 // -------------------------------------
856
857 #ifdef U_USE_TIMEZONE_OBSOLETE_2_8
858
859 const UnicodeString**
860 TimeZone::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.
865
866 numIDs = 0;
867 if (!loadOlsonIDs()) {
868 return 0;
869 }
870
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 }
878
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]
890 }
891 delete z;
892 }
893
894 return ids;
895 }
896
897 // -------------------------------------
898
899 const UnicodeString**
900 TimeZone::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.
905
906 numIDs = 0;
907 if (!loadOlsonIDs()) {
908 return 0;
909 }
910
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 }
944 }
945 }
946 ures_close(&res);
947 }
948 ures_close(ares);
949 ures_close(top);
950
951 return ids;
952 }
953
954 // -------------------------------------
955
956 const UnicodeString**
957 TimeZone::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.
962 numIDs = 0;
963 if (!loadOlsonIDs()) {
964 return 0;
965 }
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 }
974 }
975
976 return ids;
977 }
978
979 #endif
980
981 // ---------------------------------------
982
983 int32_t U_EXPORT2
984 TimeZone::countEquivalentIDs(const UnicodeString& id) {
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)));
1005 }
1006 ures_close(&res);
1007 ures_close(top);
1008 return result;
1009 }
1010
1011 // ---------------------------------------
1012
1013 const UnicodeString U_EXPORT2
1014 TimeZone::getEquivalentID(const UnicodeString& id, int32_t index) {
1015 U_DEBUG_TZ_MSG(("gEI(%d)\n", index));
1016 UnicodeString result;
1017 UErrorCode ec = U_ZERO_ERROR;
1018 UResourceBundle res;
1019 ures_initStackObject(&res);
1020 UResourceBundle *top = openOlsonResource(id, res, ec);
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];
1031 }
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)));
1043 }
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)));
1050 }
1051 #endif
1052 return result;
1053 }
1054
1055 // ---------------------------------------
1056
1057
1058 UnicodeString&
1059 TimeZone::getDisplayName(UnicodeString& result) const
1060 {
1061 return getDisplayName(FALSE,LONG,Locale::getDefault(), result);
1062 }
1063
1064 UnicodeString&
1065 TimeZone::getDisplayName(const Locale& locale, UnicodeString& result) const
1066 {
1067 return getDisplayName(FALSE, LONG, locale, result);
1068 }
1069
1070 UnicodeString&
1071 TimeZone::getDisplayName(UBool daylight, EDisplayType style, UnicodeString& result) const
1072 {
1073 return getDisplayName(daylight,style, Locale::getDefault(), result);
1074 }
1075
1076 UnicodeString&
1077 TimeZone::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;
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));
1087 if(!U_SUCCESS(status))
1088 {
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();
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
1110 format.applyPattern(style == LONG ? ZZZZ_STR : Z_STR);
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 */
1128 TimeZone*
1129 TimeZone::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
1207 UBool
1208 TimeZone::hasSameRules(const TimeZone& other) const
1209 {
1210 return (getRawOffset() == other.getRawOffset() &&
1211 useDaylightTime() == other.useDaylightTime());
1212 }
1213
1214 U_NAMESPACE_END
1215
1216 #endif /* #if !UCONFIG_NO_FORMATTING */
1217
1218 //eof