]> git.saurik.com Git - apple/icu.git/blame - icuSources/i18n/timezone.cpp
ICU-400.42.tar.gz
[apple/icu.git] / icuSources / i18n / timezone.cpp
CommitLineData
b75a7d8f
A
1/*
2*******************************************************************************
46f4442e 3* Copyright (C) 1997-2009, 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"
46f4442e 82#include "zonemeta.h"
b75a7d8f 83
374ca955
A
84#define kZONEINFO "zoneinfo"
85#define kREGIONS "Regions"
86#define kZONES "Zones"
87#define kRULES "Rules"
88#define kNAMES "Names"
89#define kDEFAULT "Default"
46f4442e
A
90#define kMAX_CUSTOM_HOUR 23
91#define kMAX_CUSTOM_MIN 59
92#define kMAX_CUSTOM_SEC 59
93#define MINUS 0x002D
94#define PLUS 0x002B
95#define ZERO_DIGIT 0x0030
b75a7d8f
A
96
97// Static data and constants
98
99static const UChar GMT_ID[] = {0x47, 0x4D, 0x54, 0x00}; /* "GMT" */
374ca955
A
100static const UChar Z_STR[] = {0x7A, 0x00}; /* "z" */
101static const UChar ZZZZ_STR[] = {0x7A, 0x7A, 0x7A, 0x7A, 0x00}; /* "zzzz" */
b75a7d8f 102static const int32_t GMT_ID_LENGTH = 3;
b75a7d8f 103
46f4442e
A
104static UMTX LOCK;
105static UMTX TZSET_LOCK;
106static U_NAMESPACE_QUALIFIER TimeZone* DEFAULT_ZONE = NULL;
107static U_NAMESPACE_QUALIFIER TimeZone* _GMT = NULL; // cf. TimeZone::GMT
108
109static char TZDATA_VERSION[16];
b75a7d8f 110
374ca955 111#ifdef U_USE_TIMEZONE_OBSOLETE_2_8
46f4442e 112static U_NAMESPACE_QUALIFIER UnicodeString* OLSON_IDS = 0;
374ca955 113#endif
b75a7d8f 114
374ca955 115U_CDECL_BEGIN
73c04bcf 116static UBool U_CALLCONV timeZone_cleanup(void)
374ca955
A
117{
118#ifdef U_USE_TIMEZONE_OBSOLETE_2_8
119 delete []OLSON_IDS;
120 OLSON_IDS = 0;
121#endif
b75a7d8f
A
122
123 delete DEFAULT_ZONE;
124 DEFAULT_ZONE = NULL;
125
126 delete _GMT;
127 _GMT = NULL;
128
46f4442e
A
129 uprv_memset(TZDATA_VERSION, 0, sizeof(TZDATA_VERSION));
130
b75a7d8f
A
131 if (LOCK) {
132 umtx_destroy(&LOCK);
133 LOCK = NULL;
134 }
46f4442e
A
135 if (TZSET_LOCK) {
136 umtx_destroy(&TZSET_LOCK);
137 TZSET_LOCK = NULL;
138 }
b75a7d8f
A
139
140 return TRUE;
141}
374ca955 142U_CDECL_END
b75a7d8f
A
143
144U_NAMESPACE_BEGIN
145
146/**
374ca955
A
147 * The Olson data is stored the "zoneinfo" resource bundle.
148 * Sub-resources are organized into three ranges of data: Zones, final
149 * rules, and country tables. There is also a meta-data resource
150 * which has 3 integers: The number of zones, rules, and countries,
151 * respectively. The country count includes the non-country 'Default'.
b75a7d8f 152 */
374ca955 153static int32_t OLSON_ZONE_COUNT = 0; // count of zones
b75a7d8f 154
374ca955
A
155/**
156 * Given a pointer to an open "zoneinfo" resource, load up the Olson
157 * meta-data. Return TRUE if successful.
158 */
159static UBool getOlsonMeta(const UResourceBundle* top) {
46f4442e 160 if (OLSON_ZONE_COUNT == 0) {
374ca955
A
161 UErrorCode ec = U_ZERO_ERROR;
162 UResourceBundle res;
163 ures_initStackObject(&res);
164 ures_getByKey(top, kZONES, &res, &ec);
165 if(U_SUCCESS(ec)) {
46f4442e
A
166 OLSON_ZONE_COUNT = ures_getSize(&res);
167 U_DEBUG_TZ_MSG(("OZC%d\n",OLSON_ZONE_COUNT));
374ca955
A
168 }
169 ures_close(&res);
170 }
46f4442e 171 return (OLSON_ZONE_COUNT > 0);
374ca955
A
172}
173
174/**
175 * Load up the Olson meta-data. Return TRUE if successful.
176 */
177static UBool getOlsonMeta() {
46f4442e 178 if (OLSON_ZONE_COUNT == 0) {
374ca955
A
179 UErrorCode ec = U_ZERO_ERROR;
180 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
181 if (U_SUCCESS(ec)) {
46f4442e 182 getOlsonMeta(top);
374ca955
A
183 }
184 ures_close(top);
185 }
46f4442e 186 return (OLSON_ZONE_COUNT > 0);
374ca955
A
187}
188
189static int32_t findInStringArray(UResourceBundle* array, const UnicodeString& id, UErrorCode &status)
190{
191 UnicodeString copy;
73c04bcf
A
192 const UChar *u;
193 int32_t len;
374ca955 194
374ca955 195 int32_t start = 0;
73c04bcf
A
196 int32_t limit = ures_getSize(array);
197 int32_t mid;
198 int32_t lastMid = INT32_MAX;
199 if(U_FAILURE(status) || (limit < 1)) {
374ca955
A
200 return -1;
201 }
73c04bcf 202 U_DEBUG_TZ_MSG(("fisa: Looking for %s, between %d and %d\n", U_DEBUG_TZ_STR(UnicodeString(id).getTerminatedBuffer()), start, limit));
374ca955 203
73c04bcf
A
204 for (;;) {
205 mid = (int32_t)((start + limit) / 2);
206 if (lastMid == mid) { /* Have we moved? */
207 break; /* We haven't moved, and it wasn't found. */
208 }
209 lastMid = mid;
210 u = ures_getStringByIndex(array, mid, &len, &status);
211 if (U_FAILURE(status)) {
212 break;
213 }
214 U_DEBUG_TZ_MSG(("tz: compare to %s, %d .. [%d] .. %d\n", U_DEBUG_TZ_STR(u), start, mid, limit));
215 copy.setTo(TRUE, u, len);
216 int r = id.compare(copy);
217 if(r==0) {
218 U_DEBUG_TZ_MSG(("fisa: found at %d\n", mid));
219 return mid;
374ca955 220 } else if(r<0) {
73c04bcf 221 limit = mid;
374ca955 222 } else {
73c04bcf 223 start = mid;
374ca955
A
224 }
225 }
374ca955
A
226 U_DEBUG_TZ_MSG(("fisa: not found\n"));
227 return -1;
228}
229
230/**
231 * Fetch a specific zone by name. Replaces the getByKey call.
232 * @param top Top timezone resource
233 * @param id Time zone ID
234 * @param oldbundle Bundle for reuse (or NULL). see 'ures_open()'
235 * @return the zone's bundle if found, or undefined if error. Reuses oldbundle.
236 */
237static UResourceBundle* getZoneByName(const UResourceBundle* top, const UnicodeString& id, UResourceBundle *oldbundle, UErrorCode& status) {
238 // load the Rules object
239 UResourceBundle *tmp = ures_getByKey(top, kNAMES, NULL, &status);
240
241 // search for the string
242 int32_t idx = findInStringArray(tmp, id, status);
243
244 if((idx == -1) && U_SUCCESS(status)) {
245 // not found
246 status = U_MISSING_RESOURCE_ERROR;
247 //ures_close(oldbundle);
248 //oldbundle = NULL;
249 } else {
250 U_DEBUG_TZ_MSG(("gzbn: oldbundle= size %d, type %d, %s\n", ures_getSize(tmp), ures_getType(tmp), u_errorName(status)));
251 tmp = ures_getByKey(top, kZONES, tmp, &status); // get Zones object from top
252 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)));
253 oldbundle = ures_getByIndex(tmp, idx, oldbundle, &status); // get nth Zone object
254 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 255 }
374ca955
A
256 ures_close(tmp);
257 if(U_FAILURE(status)) {
258 //ures_close(oldbundle);
259 return NULL;
260 } else {
261 return oldbundle;
262 }
263}
b75a7d8f 264
b75a7d8f 265
374ca955
A
266UResourceBundle* TimeZone::loadRule(const UResourceBundle* top, const UnicodeString& ruleid, UResourceBundle* oldbundle, UErrorCode& status) {
267 char key[64];
268 ruleid.extract(0, sizeof(key)-1, key, (int32_t)sizeof(key)-1, US_INV);
269 U_DEBUG_TZ_MSG(("loadRule(%s)\n", key));
270 UResourceBundle *r = ures_getByKey(top, kRULES, oldbundle, &status);
271 U_DEBUG_TZ_MSG(("loadRule(%s) -> kRULES [%s]\n", key, u_errorName(status)));
272 r = ures_getByKey(r, key, r, &status);
273 U_DEBUG_TZ_MSG(("loadRule(%s) -> item [%s]\n", key, u_errorName(status)));
274 return r;
275}
b75a7d8f 276
374ca955
A
277/**
278 * Given an ID, open the appropriate resource for the given time zone.
279 * Dereference aliases if necessary.
280 * @param id zone id
281 * @param res resource, which must be ready for use (initialized but not open)
282 * @param ec input-output error code
283 * @return top-level resource bundle
284 */
285static UResourceBundle* openOlsonResource(const UnicodeString& id,
286 UResourceBundle& res,
287 UErrorCode& ec)
288{
289#if U_DEBUG_TZ
290 char buf[128];
291 id.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
292#endif
293 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
294 U_DEBUG_TZ_MSG(("pre: res sz=%d\n", ures_getSize(&res)));
295 /* &res = */ getZoneByName(top, id, &res, ec);
296 // Dereference if this is an alias. Docs say result should be 1
297 // but it is 0 in 2.8 (?).
298 U_DEBUG_TZ_MSG(("Loading zone '%s' (%s, size %d) - %s\n", buf, ures_getKey((UResourceBundle*)&res), ures_getSize(&res), u_errorName(ec)));
299 if (ures_getSize(&res) <= 1 && getOlsonMeta(top)) {
300 int32_t deref = ures_getInt(&res, &ec) + 0;
301 U_DEBUG_TZ_MSG(("getInt: %s - type is %d\n", u_errorName(ec), ures_getType(&res)));
302 UResourceBundle *ares = ures_getByKey(top, kZONES, NULL, &ec); // dereference Zones section
303 ures_getByIndex(ares, deref, &res, &ec);
304 ures_close(ares);
305 U_DEBUG_TZ_MSG(("alias to #%d (%s) - %s\n", deref, "??", u_errorName(ec)));
306 } else {
307 U_DEBUG_TZ_MSG(("not an alias - size %d\n", ures_getSize(&res)));
308 }
309 U_DEBUG_TZ_MSG(("%s - final status is %s\n", buf, u_errorName(ec)));
310 return top;
311}
312
313#ifdef U_USE_TIMEZONE_OBSOLETE_2_8
314
315/**
316 * Load all the ids from the "zoneinfo" resource bundle into a static
317 * array that we hang onto. This is _only_ used to implement the
318 * deprecated createAvailableIDs() API.
319 */
320static UBool loadOlsonIDs() {
321 if (OLSON_IDS != 0) {
322 return TRUE;
b75a7d8f 323 }
374ca955
A
324
325 UErrorCode ec = U_ZERO_ERROR;
326 UnicodeString* ids = 0;
327 int32_t count = 0;
328 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
329 UResourceBundle *nres = ures_getByKey(top, kNAMES, NULL, &ec); // dereference Names section
330 if (U_SUCCESS(ec)) {
331 getOlsonMeta(top);
332 int32_t start = 0;
333 count = ures_getSize(nres);
334 ids = new UnicodeString[(count > 0) ? count : 1];
46f4442e
A
335 // Null pointer check
336 if (ids != NULL) {
337 for (int32_t i=0; i<count; ++i) {
338 int32_t idLen = 0;
339 const UChar* id = ures_getStringByIndex(nres, i, &idLen, &ec);
340 ids[i].fastCopyFrom(UnicodeString(TRUE, id, idLen));
341 if (U_FAILURE(ec)) {
342 break;
343 }
374ca955 344 }
46f4442e
A
345 } else {
346 ec = U_MEMORY_ALLOCATION_ERROR;
374ca955
A
347 }
348 }
349 ures_close(nres);
350 ures_close(top);
351
352 if (U_FAILURE(ec)) {
353 delete[] ids;
354 return FALSE;
b75a7d8f
A
355 }
356
357 // Keep mutexed operations as short as possible by doing all
358 // computations first, then doing pointer copies within the mutex.
359 umtx_lock(&LOCK);
374ca955
A
360 if (OLSON_IDS == 0) {
361 OLSON_IDS = ids;
362 ids = 0;
363 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
b75a7d8f
A
364 }
365 umtx_unlock(&LOCK);
366
367 // If another thread initialized the statics first, then delete
368 // our unused data.
374ca955 369 delete[] ids;
b75a7d8f
A
370 return TRUE;
371}
372
374ca955 373#endif
b75a7d8f
A
374
375// -------------------------------------
376
374ca955 377const TimeZone* U_EXPORT2
b75a7d8f
A
378TimeZone::getGMT(void)
379{
46f4442e
A
380 UBool needsInit;
381 UMTX_CHECK(&LOCK, (_GMT == NULL), needsInit); /* This is here to prevent race conditions. */
382
b75a7d8f
A
383 // Initialize _GMT independently of other static data; it should
384 // be valid even if we can't load the time zone UDataMemory.
46f4442e
A
385 if (needsInit) {
386 umtx_lock(&LOCK);
387 if (_GMT == 0) {
388 _GMT = new SimpleTimeZone(0, UnicodeString(TRUE, GMT_ID, GMT_ID_LENGTH));
389 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
390 }
391 umtx_unlock(&LOCK);
b75a7d8f
A
392 }
393 return _GMT;
394}
395
396// *****************************************************************************
397// class TimeZone
398// *****************************************************************************
399
374ca955
A
400UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(TimeZone)
401
b75a7d8f
A
402TimeZone::TimeZone()
403 : UObject(), fID()
404{
405}
406
407// -------------------------------------
408
409TimeZone::TimeZone(const UnicodeString &id)
410 : UObject(), fID(id)
411{
412}
413
414// -------------------------------------
415
416TimeZone::~TimeZone()
417{
418}
419
420// -------------------------------------
421
422TimeZone::TimeZone(const TimeZone &source)
423 : UObject(source), fID(source.fID)
424{
425}
426
427// -------------------------------------
428
429TimeZone &
430TimeZone::operator=(const TimeZone &right)
431{
432 if (this != &right) fID = right.fID;
433 return *this;
434}
435
436// -------------------------------------
437
438UBool
439TimeZone::operator==(const TimeZone& that) const
440{
441 return getDynamicClassID() == that.getDynamicClassID() &&
442 fID == that.fID;
443}
444
445// -------------------------------------
446
374ca955 447TimeZone* U_EXPORT2
b75a7d8f
A
448TimeZone::createTimeZone(const UnicodeString& ID)
449{
450 /* We first try to lookup the zone ID in our system list. If this
451 * fails, we try to parse it as a custom string GMT[+-]hh:mm. If
452 * all else fails, we return GMT, which is probably not what the
453 * user wants, but at least is a functioning TimeZone object.
374ca955
A
454 *
455 * We cannot return NULL, because that would break compatibility
456 * with the JDK.
b75a7d8f 457 */
374ca955 458 TimeZone* result = createSystemTimeZone(ID);
b75a7d8f 459
b75a7d8f 460 if (result == 0) {
374ca955 461 U_DEBUG_TZ_MSG(("failed to load system time zone with id - falling to custom"));
b75a7d8f
A
462 result = createCustomTimeZone(ID);
463 }
464 if (result == 0) {
374ca955 465 U_DEBUG_TZ_MSG(("failed to load time zone with id - falling to GMT"));
46f4442e
A
466 const TimeZone* temptz = getGMT();
467 if (temptz == NULL) {
468 result = NULL;
469 } else {
470 result = temptz->clone();
471 }
b75a7d8f
A
472 }
473 return result;
474}
475
b75a7d8f
A
476/**
477 * Lookup the given name in our system zone table. If found,
478 * instantiate a new zone of that name and return it. If not
479 * found, return 0.
b75a7d8f
A
480 */
481TimeZone*
374ca955
A
482TimeZone::createSystemTimeZone(const UnicodeString& id) {
483 TimeZone* z = 0;
484 UErrorCode ec = U_ZERO_ERROR;
485 UResourceBundle res;
486 ures_initStackObject(&res);
487 U_DEBUG_TZ_MSG(("pre-err=%s\n", u_errorName(ec)));
488 UResourceBundle *top = openOlsonResource(id, res, ec);
489 U_DEBUG_TZ_MSG(("post-err=%s\n", u_errorName(ec)));
490 if (U_SUCCESS(ec)) {
491 z = new OlsonTimeZone(top, &res, ec);
492 if (z) {
493 z->setID(id);
494 } else {
495 U_DEBUG_TZ_MSG(("cstz: olson time zone failed to initialize - err %s\n", u_errorName(ec)));
496 }
497 }
498 ures_close(&res);
499 ures_close(top);
500 if (U_FAILURE(ec)) {
501 U_DEBUG_TZ_MSG(("cstz: failed to create, err %s\n", u_errorName(ec)));
502 delete z;
503 z = 0;
b75a7d8f 504 }
374ca955 505 return z;
b75a7d8f
A
506}
507
508// -------------------------------------
509
510/**
511 * Initialize DEFAULT_ZONE from the system default time zone. The
512 * caller should confirm that DEFAULT_ZONE is NULL before calling.
513 * Upon return, DEFAULT_ZONE will not be NULL, unless operator new()
514 * returns NULL.
515 *
516 * Must be called OUTSIDE mutex.
517 */
518void
519TimeZone::initDefault()
520{
521 // We access system timezone data through TPlatformUtilities,
522 // including tzset(), timezone, and tzname[].
523 int32_t rawOffset = 0;
524 const char *hostID;
525
526 // First, try to create a system timezone, based
527 // on the string ID in tzname[0].
528 {
46f4442e
A
529 // NOTE: Local mutex here. TimeZone mutex below
530 // mutexed to avoid threading issues in the platform functions.
531 // Some of the locale/timezone OS functions may not be thread safe,
532 // so the intent is that any setting from anywhere within ICU
533 // happens while the ICU mutex is held.
534 // The operating system might actually use ICU to implement timezones.
535 // So we may have ICU calling ICU here, like on AIX.
536 // In order to prevent a double lock of a non-reentrant mutex in a
537 // different part of ICU, we use TZSET_LOCK to allow only one instance
538 // of ICU to query these thread unsafe OS functions at any given time.
539 Mutex lock(&TZSET_LOCK);
540
541 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
b75a7d8f
A
542 uprv_tzset(); // Initialize tz... system data
543
544 // Get the timezone ID from the host. This function should do
545 // any required host-specific remapping; e.g., on Windows this
546 // function maps the Date and Time control panel setting to an
547 // ICU timezone ID.
548 hostID = uprv_tzname(0);
549
550 // Invert sign because UNIX semantics are backwards
551 rawOffset = uprv_timezone() * -U_MILLIS_PER_SECOND;
552 }
553
46f4442e
A
554 UBool initialized;
555 UMTX_CHECK(&LOCK, (DEFAULT_ZONE != NULL), initialized);
556 if (initialized) {
557 /* Hrmph? Either a race condition happened, or tzset initialized ICU. */
558 return;
559 }
560
b75a7d8f
A
561 TimeZone* default_zone = NULL;
562
374ca955
A
563 /* Make sure that the string is NULL terminated to prevent BoundsChecker/Purify warnings. */
564 UnicodeString hostStrID(hostID, -1, US_INV);
565 hostStrID.append((UChar)0);
566 hostStrID.truncate(hostStrID.length()-1);
567 default_zone = createSystemTimeZone(hostStrID);
568
73c04bcf
A
569 int32_t hostIDLen = hostStrID.length();
570 if (default_zone != NULL && rawOffset != default_zone->getRawOffset()
571 && (3 <= hostIDLen && hostIDLen <= 4))
572 {
573 // Uh oh. This probably wasn't a good id.
574 // It was probably an ambiguous abbreviation
575 delete default_zone;
576 default_zone = NULL;
577 }
578
374ca955
A
579#if 0
580 // NOTE: As of ICU 2.8, we no longer have an offsets table, since
581 // historical zones can change offset over time. If we add
582 // build-time heuristics to infer the "most frequent" raw offset
583 // of a zone, we can build tables and institute defaults, as done
584 // in ICU <= 2.6.
585
586 // If we couldn't get the time zone ID from the host, use
587 // the default host timezone offset. Further refinements
588 // to this include querying the host to determine if DST
589 // is in use or not and possibly using the host locale to
590 // select from multiple zones at a the same offset. We
591 // don't do any of this now, but we could easily add this.
592 if (default_zone == NULL) {
593 // Use the designated default in the time zone list that has the
594 // appropriate GMT offset, if there is one.
595
596 const OffsetIndex* index = INDEX_BY_OFFSET;
597
598 for (;;) {
599 if (index->gmtOffset > rawOffset) {
600 // Went past our desired offset; no match found
601 break;
602 }
603 if (index->gmtOffset == rawOffset) {
604 // Found our desired offset
605 default_zone = createSystemTimeZone(ZONE_IDS[index->defaultZone]);
606 break;
b75a7d8f 607 }
374ca955
A
608 // Compute the position of the next entry. If the delta value
609 // in this entry is zero, then there is no next entry.
610 uint16_t delta = index->nextEntryDelta;
611 if (delta == 0) {
612 break;
613 }
614 index = (const OffsetIndex*)((int8_t*)index + delta);
b75a7d8f
A
615 }
616 }
374ca955 617#endif
b75a7d8f 618
374ca955
A
619 // Construct a fixed standard zone with the host's ID
620 // and raw offset.
621 if (default_zone == NULL) {
622 default_zone = new SimpleTimeZone(rawOffset, hostStrID);
623 }
624
625 // If we _still_ don't have a time zone, use GMT.
b75a7d8f 626 if (default_zone == NULL) {
46f4442e
A
627 const TimeZone* temptz = getGMT();
628 // If we can't use GMT, get out.
629 if (temptz == NULL) {
630 return;
631 }
632 default_zone = temptz->clone();
b75a7d8f
A
633 }
634
635 // If DEFAULT_ZONE is still NULL, set it up.
636 umtx_lock(&LOCK);
637 if (DEFAULT_ZONE == NULL) {
638 DEFAULT_ZONE = default_zone;
639 default_zone = NULL;
374ca955 640 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
b75a7d8f
A
641 }
642 umtx_unlock(&LOCK);
643
644 delete default_zone;
645}
646
647// -------------------------------------
648
374ca955 649TimeZone* U_EXPORT2
b75a7d8f
A
650TimeZone::createDefault()
651{
46f4442e
A
652 /* This is here to prevent race conditions. */
653 UBool needsInit;
654 UMTX_CHECK(&LOCK, (DEFAULT_ZONE == NULL), needsInit);
655 if (needsInit) {
b75a7d8f
A
656 initDefault();
657 }
658
659 Mutex lock(&LOCK); // In case adoptDefault is called
46f4442e 660 return (DEFAULT_ZONE != NULL) ? DEFAULT_ZONE->clone() : NULL;
b75a7d8f
A
661}
662
663// -------------------------------------
664
374ca955 665void U_EXPORT2
b75a7d8f
A
666TimeZone::adoptDefault(TimeZone* zone)
667{
668 if (zone != NULL)
669 {
670 TimeZone* old = NULL;
671
672 umtx_init(&LOCK); /* This is here to prevent race conditions. */
673 umtx_lock(&LOCK);
674 old = DEFAULT_ZONE;
675 DEFAULT_ZONE = zone;
676 umtx_unlock(&LOCK);
677
678 delete old;
374ca955 679 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
b75a7d8f
A
680 }
681}
682// -------------------------------------
683
374ca955 684void U_EXPORT2
b75a7d8f
A
685TimeZone::setDefault(const TimeZone& zone)
686{
687 adoptDefault(zone.clone());
688}
689
374ca955
A
690//----------------------------------------------------------------------
691
692/**
693 * This is the default implementation for subclasses that do not
694 * override this method. This implementation calls through to the
695 * 8-argument getOffset() method after suitable computations, and
696 * correctly adjusts GMT millis to local millis when necessary.
697 */
698void TimeZone::getOffset(UDate date, UBool local, int32_t& rawOffset,
699 int32_t& dstOffset, UErrorCode& ec) const {
700 if (U_FAILURE(ec)) {
701 return;
702 }
703
704 rawOffset = getRawOffset();
374ca955
A
705 if (!local) {
706 date += rawOffset; // now in local standard millis
707 }
708
46f4442e
A
709 // When local == TRUE, date might not be in local standard
710 // millis. getOffset taking 7 parameters used here assume
711 // the given time in day is local standard time.
712 // At STD->DST transition, there is a range of time which
713 // does not exist. When 'date' is in this time range
714 // (and local == TRUE), this method interprets the specified
715 // local time as DST. At DST->STD transition, there is a
716 // range of time which occurs twice. In this case, this
717 // method interprets the specified local time as STD.
718 // To support the behavior above, we need to call getOffset
719 // (with 7 args) twice when local == true and DST is
720 // detected in the initial call.
374ca955
A
721 for (int32_t pass=0; ; ++pass) {
722 int32_t year, month, dom, dow;
723 double day = uprv_floor(date / U_MILLIS_PER_DAY);
724 int32_t millis = (int32_t) (date - day * U_MILLIS_PER_DAY);
46f4442e 725
374ca955 726 Grego::dayToFields(day, year, month, dom, dow);
46f4442e 727
374ca955
A
728 dstOffset = getOffset(GregorianCalendar::AD, year, month, dom,
729 (uint8_t) dow, millis,
730 Grego::monthLength(year, month),
731 ec) - rawOffset;
732
46f4442e
A
733 // Recompute if local==TRUE, dstOffset!=0.
734 if (pass!=0 || !local || dstOffset == 0) {
374ca955
A
735 break;
736 }
46f4442e
A
737 // adjust to local standard millis
738 date -= dstOffset;
374ca955
A
739 }
740}
741
b75a7d8f
A
742// -------------------------------------
743
744// New available IDs API as of ICU 2.4. Uses StringEnumeration API.
745
746class TZEnumeration : public StringEnumeration {
73c04bcf
A
747private:
748
374ca955
A
749 // Map into to zones. Our results are zone[map[i]] for
750 // i=0..len-1, where zone[i] is the i-th Olson zone. If map==NULL
751 // then our results are zone[i] for i=0..len-1. Len will be zero
752 // iff the zone data could not be loaded.
b75a7d8f
A
753 int32_t* map;
754 int32_t len;
755 int32_t pos;
b75a7d8f 756
73c04bcf
A
757 UBool getID(int32_t i) {
758 UErrorCode ec = U_ZERO_ERROR;
759 int32_t idLen = 0;
760 const UChar* id = NULL;
761 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
762 top = ures_getByKey(top, kNAMES, top, &ec); // dereference Zones section
763 id = ures_getStringByIndex(top, i, &idLen, &ec);
764 if(U_FAILURE(ec)) {
765 unistr.truncate(0);
766 }
767 else {
768 unistr.fastCopyFrom(UnicodeString(TRUE, id, idLen));
769 }
770 ures_close(top);
771 return U_SUCCESS(ec);
772 }
773
b75a7d8f 774public:
374ca955
A
775 TZEnumeration() : map(NULL), len(0), pos(0) {
776 if (getOlsonMeta()) {
777 len = OLSON_ZONE_COUNT;
b75a7d8f
A
778 }
779 }
780
374ca955
A
781 TZEnumeration(int32_t rawOffset) : map(NULL), len(0), pos(0) {
782 if (!getOlsonMeta()) {
783 return;
784 }
b75a7d8f 785
374ca955
A
786 // Allocate more space than we'll need. The end of the array will
787 // be blank.
788 map = (int32_t*)uprv_malloc(OLSON_ZONE_COUNT * sizeof(int32_t));
789 if (map == 0) {
b75a7d8f
A
790 return;
791 }
792
374ca955
A
793 uprv_memset(map, 0, sizeof(int32_t) * OLSON_ZONE_COUNT);
794
795 UnicodeString s;
796 for (int32_t i=0; i<OLSON_ZONE_COUNT; ++i) {
797 if (getID(i)) {
798 // This is VERY inefficient.
799 TimeZone* z = TimeZone::createTimeZone(unistr);
800 // Make sure we get back the ID we wanted (if the ID is
801 // invalid we get back GMT).
802 if (z != 0 && z->getID(s) == unistr &&
803 z->getRawOffset() == rawOffset) {
804 map[len++] = i;
b75a7d8f 805 }
374ca955 806 delete z;
b75a7d8f 807 }
b75a7d8f
A
808 }
809 }
810
374ca955
A
811 TZEnumeration(const char* country) : map(NULL), len(0), pos(0) {
812 if (!getOlsonMeta()) {
b75a7d8f
A
813 return;
814 }
815
374ca955
A
816 char key[] = {0, 0, 0, 0,0, 0, 0,0, 0, 0,0}; // e.g., "US", or "Default" for no country
817 if (country) {
818 uprv_strncat(key, country, 2);
819 } else {
820 uprv_strcpy(key, kDEFAULT);
b75a7d8f
A
821 }
822
374ca955
A
823 UErrorCode ec = U_ZERO_ERROR;
824 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
825 top = ures_getByKey(top, kREGIONS, top, &ec); // dereference 'Regions' section
826 if (U_SUCCESS(ec)) {
827 UResourceBundle res;
828 ures_initStackObject(&res);
829 ures_getByKey(top, key, &res, &ec);
830 // The list of zones is a list of integers, from 0..n-1,
831 // where n is the total number of system zones.
832 const int32_t* v = ures_getIntVector(&res, &len, &ec);
833 if (U_SUCCESS(ec)) {
834 U_ASSERT(len > 0);
835 map = (int32_t*)uprv_malloc(sizeof(int32_t) * len);
836 if (map != 0) {
b75a7d8f 837 for (uint16_t i=0; i<len; ++i) {
374ca955
A
838 U_ASSERT(v[i] >= 0 && v[i] < OLSON_ZONE_COUNT);
839 map[i] = v[i];
b75a7d8f
A
840 }
841 }
374ca955
A
842 } else {
843 U_DEBUG_TZ_MSG(("Failed to load tz for region %s: %s\n", country, u_errorName(ec)));
b75a7d8f 844 }
374ca955
A
845 ures_close(&res);
846 }
847 ures_close(top);
848 }
849
850 TZEnumeration(const TZEnumeration &other) : StringEnumeration(), map(NULL), len(0), pos(0) {
851 if(other.len > 0) {
852 if(other.map != NULL) {
853 map = (int32_t *)uprv_malloc(other.len * sizeof(int32_t));
854 if(map != NULL) {
855 len = other.len;
856 uprv_memcpy(map, other.map, len * sizeof(int32_t));
857 pos = other.pos;
858 }
859 } else {
860 len = other.len;
861 pos = other.pos;
b75a7d8f 862 }
b75a7d8f
A
863 }
864 }
865
866 virtual ~TZEnumeration() {
867 uprv_free(map);
b75a7d8f
A
868 }
869
374ca955
A
870 virtual StringEnumeration *clone() const {
871 return new TZEnumeration(*this);
b75a7d8f
A
872 }
873
374ca955
A
874 virtual int32_t count(UErrorCode& status) const {
875 return U_FAILURE(status) ? 0 : len;
b75a7d8f
A
876 }
877
374ca955 878 virtual const UnicodeString* snext(UErrorCode& status) {
b75a7d8f 879 if (U_SUCCESS(status) && pos < len) {
374ca955
A
880 getID((map == 0) ? pos : map[pos]);
881 ++pos;
882 return &unistr;
b75a7d8f 883 }
374ca955 884 return 0;
b75a7d8f
A
885 }
886
374ca955 887 virtual void reset(UErrorCode& /*status*/) {
b75a7d8f
A
888 pos = 0;
889 }
890
374ca955
A
891public:
892 static UClassID U_EXPORT2 getStaticClassID(void);
893 virtual UClassID getDynamicClassID(void) const;
b75a7d8f
A
894};
895
374ca955 896UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TZEnumeration)
b75a7d8f 897
374ca955 898StringEnumeration* U_EXPORT2
b75a7d8f
A
899TimeZone::createEnumeration() {
900 return new TZEnumeration();
901}
902
374ca955 903StringEnumeration* U_EXPORT2
b75a7d8f
A
904TimeZone::createEnumeration(int32_t rawOffset) {
905 return new TZEnumeration(rawOffset);
906}
907
374ca955 908StringEnumeration* U_EXPORT2
b75a7d8f
A
909TimeZone::createEnumeration(const char* country) {
910 return new TZEnumeration(country);
911}
912
913// -------------------------------------
914
374ca955 915#ifdef U_USE_TIMEZONE_OBSOLETE_2_8
b75a7d8f
A
916
917const UnicodeString**
918TimeZone::createAvailableIDs(int32_t rawOffset, int32_t& numIDs)
919{
920 // We are creating a new array to existing UnicodeString pointers.
921 // The caller will delete the array when done, but not the pointers
922 // in the array.
374ca955
A
923
924 numIDs = 0;
925 if (!loadOlsonIDs()) {
b75a7d8f
A
926 return 0;
927 }
928
374ca955
A
929 // Allocate more space than we'll need. The end of the array will
930 // be blank.
931 const UnicodeString** ids =
932 (const UnicodeString** )uprv_malloc(OLSON_ZONE_COUNT * sizeof(UnicodeString *));
933 if (ids == 0) {
934 return 0;
935 }
b75a7d8f 936
374ca955
A
937 uprv_memset(ids, 0, sizeof(UnicodeString*) * OLSON_ZONE_COUNT);
938
939 UnicodeString s;
940 for (int32_t i=0; i<OLSON_ZONE_COUNT; ++i) {
941 // This is VERY inefficient.
942 TimeZone* z = TimeZone::createTimeZone(OLSON_IDS[i]);
943 // Make sure we get back the ID we wanted (if the ID is
944 // invalid we get back GMT).
945 if (z != 0 && z->getID(s) == OLSON_IDS[i] &&
946 z->getRawOffset() == rawOffset) {
947 ids[numIDs++] = &OLSON_IDS[i]; // [sic]
b75a7d8f 948 }
374ca955 949 delete z;
b75a7d8f
A
950 }
951
374ca955 952 return ids;
b75a7d8f
A
953}
954
955// -------------------------------------
956
957const UnicodeString**
958TimeZone::createAvailableIDs(const char* country, int32_t& numIDs) {
959
960 // We are creating a new array to existing UnicodeString pointers.
961 // The caller will delete the array when done, but not the pointers
962 // in the array.
b75a7d8f 963
374ca955
A
964 numIDs = 0;
965 if (!loadOlsonIDs()) {
966 return 0;
b75a7d8f
A
967 }
968
374ca955
A
969 char key[] = { 0, 0, 0,0, 0, 0,0, 0, 0 }; // e.g., "US", or "Default" for non-country zones
970 if (country) {
971 uprv_strncat(key, country, 2);
972 } else {
973 uprv_strcpy(key, kDEFAULT);
974 }
975
976 const UnicodeString** ids = 0;
977
978 UErrorCode ec = U_ZERO_ERROR;
979 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
980 UResourceBundle *ares = ures_getByKey(top, kREGIONS, NULL, &ec); // dereference Regions section
981 if (U_SUCCESS(ec)) {
982 getOlsonMeta(top);
983 UResourceBundle res;
984 ures_initStackObject(&res);
985 ures_getByKey(ares, key, &res, &ec);
986 U_DEBUG_TZ_MSG(("caI: on %s, err %s\n", country, u_errorName(ec)));
987 if (U_SUCCESS(ec)) {
988 /* The list of zones is a list of integers, from 0..n-1,
989 * where n is the total number of system zones. The
990 * numbering corresponds exactly to the ordering of
991 * OLSON_IDS.
992 */
993 const int32_t* v = ures_getIntVector(&res, &numIDs, &ec);
994 ids = (const UnicodeString**)
995 uprv_malloc(numIDs * sizeof(UnicodeString*));
996 if (ids == 0) {
997 numIDs = 0;
998 } else {
999 for (int32_t i=0; i<numIDs; ++i) {
1000 ids[i] = &OLSON_IDS[v[i]]; // [sic]
1001 }
b75a7d8f 1002 }
b75a7d8f 1003 }
374ca955 1004 ures_close(&res);
b75a7d8f 1005 }
374ca955
A
1006 ures_close(ares);
1007 ures_close(top);
b75a7d8f 1008
374ca955 1009 return ids;
b75a7d8f
A
1010}
1011
1012// -------------------------------------
1013
1014const UnicodeString**
1015TimeZone::createAvailableIDs(int32_t& numIDs)
1016{
1017 // We are creating a new array to existing UnicodeString pointers.
1018 // The caller will delete the array when done, but not the pointers
1019 // in the array.
374ca955
A
1020 numIDs = 0;
1021 if (!loadOlsonIDs()) {
b75a7d8f
A
1022 return 0;
1023 }
374ca955
A
1024
1025 const UnicodeString** ids =
1026 (const UnicodeString** )uprv_malloc(OLSON_ZONE_COUNT * sizeof(UnicodeString *));
1027 if (ids != 0) {
1028 numIDs = OLSON_ZONE_COUNT;
1029 for (int32_t i=0; i<numIDs; ++i) {
1030 ids[i] = &OLSON_IDS[i];
1031 }
b75a7d8f
A
1032 }
1033
374ca955 1034 return ids;
b75a7d8f
A
1035}
1036
374ca955 1037#endif
b75a7d8f
A
1038
1039// ---------------------------------------
1040
374ca955 1041int32_t U_EXPORT2
b75a7d8f 1042TimeZone::countEquivalentIDs(const UnicodeString& id) {
374ca955
A
1043 int32_t result = 0;
1044 UErrorCode ec = U_ZERO_ERROR;
1045 UResourceBundle res;
1046 ures_initStackObject(&res);
1047 U_DEBUG_TZ_MSG(("countEquivalentIDs..\n"));
1048 UResourceBundle *top = openOlsonResource(id, res, ec);
1049 if (U_SUCCESS(ec)) {
1050 int32_t size = ures_getSize(&res);
1051 U_DEBUG_TZ_MSG(("cEI: success (size %d, key %s)..\n", size, ures_getKey(&res)));
1052 if (size == 4 || size == 6) {
1053 UResourceBundle r;
1054 ures_initStackObject(&r);
1055 ures_getByIndex(&res, size-1, &r, &ec);
1056 //result = ures_getSize(&r); // doesn't work
1057 ures_getIntVector(&r, &result, &ec);
1058 U_DEBUG_TZ_MSG(("ceI: result %d, err %s\n", result, u_errorName(ec)));
1059 ures_close(&r);
1060 }
1061 } else {
1062 U_DEBUG_TZ_MSG(("cEI: fail, %s\n", u_errorName(ec)));
b75a7d8f 1063 }
374ca955
A
1064 ures_close(&res);
1065 ures_close(top);
1066 return result;
b75a7d8f
A
1067}
1068
1069// ---------------------------------------
1070
374ca955 1071const UnicodeString U_EXPORT2
b75a7d8f 1072TimeZone::getEquivalentID(const UnicodeString& id, int32_t index) {
374ca955
A
1073 U_DEBUG_TZ_MSG(("gEI(%d)\n", index));
1074 UnicodeString result;
1075 UErrorCode ec = U_ZERO_ERROR;
1076 UResourceBundle res;
1077 ures_initStackObject(&res);
1078 UResourceBundle *top = openOlsonResource(id, res, ec);
1079 int32_t zone = -1;
1080 if (U_SUCCESS(ec)) {
1081 int32_t size = ures_getSize(&res);
1082 if (size == 4 || size == 6) {
1083 UResourceBundle r;
1084 ures_initStackObject(&r);
1085 ures_getByIndex(&res, size-1, &r, &ec);
1086 const int32_t* v = ures_getIntVector(&r, &size, &ec);
1087 if (index >= 0 && index < size && getOlsonMeta()) {
1088 zone = v[index];
b75a7d8f 1089 }
374ca955
A
1090 ures_close(&r);
1091 }
1092 }
1093 ures_close(&res);
1094 if (zone >= 0) {
1095 UResourceBundle *ares = ures_getByKey(top, kNAMES, NULL, &ec); // dereference Zones section
1096 if (U_SUCCESS(ec)) {
1097 int32_t idLen = 0;
1098 const UChar* id = ures_getStringByIndex(ares, zone, &idLen, &ec);
1099 result.fastCopyFrom(UnicodeString(TRUE, id, idLen));
1100 U_DEBUG_TZ_MSG(("gei(%d) -> %d, len%d, %s\n", index, zone, result.length(), u_errorName(ec)));
b75a7d8f 1101 }
374ca955
A
1102 ures_close(ares);
1103 }
1104 ures_close(top);
1105#if defined(U_DEBUG_TZ)
1106 if(result.length() ==0) {
1107 U_DEBUG_TZ_MSG(("equiv [__, #%d] -> 0 (%s)\n", index, u_errorName(ec)));
b75a7d8f 1108 }
374ca955
A
1109#endif
1110 return result;
b75a7d8f
A
1111}
1112
1113// ---------------------------------------
1114
46f4442e
A
1115UnicodeString&
1116TimeZone::dereferOlsonLink(const UnicodeString& linkTo, UnicodeString& linkFrom) {
1117 UErrorCode ec = U_ZERO_ERROR;
1118 linkFrom.remove();
1119 UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
1120 UResourceBundle *res = getZoneByName(top, linkTo, NULL, ec);
1121 if (U_SUCCESS(ec)) {
1122 if (ures_getSize(res) == 1) {
1123 int32_t deref = ures_getInt(res, &ec);
1124 UResourceBundle *nres = ures_getByKey(top, kNAMES, NULL, &ec); // dereference Names section
1125 int32_t len;
1126 const UChar* tmp = ures_getStringByIndex(nres, deref, &len, &ec);
1127 if (U_SUCCESS(ec)) {
1128 linkFrom.setTo(tmp, len);
1129 }
1130 ures_close(nres);
1131 } else {
1132 linkFrom.setTo(linkTo);
1133 }
1134 }
1135 ures_close(res);
1136 ures_close(top);
1137 return linkFrom;
1138}
1139
1140// ---------------------------------------
1141
b75a7d8f
A
1142
1143UnicodeString&
1144TimeZone::getDisplayName(UnicodeString& result) const
1145{
1146 return getDisplayName(FALSE,LONG,Locale::getDefault(), result);
1147}
1148
1149UnicodeString&
1150TimeZone::getDisplayName(const Locale& locale, UnicodeString& result) const
1151{
1152 return getDisplayName(FALSE, LONG, locale, result);
1153}
1154
1155UnicodeString&
1156TimeZone::getDisplayName(UBool daylight, EDisplayType style, UnicodeString& result) const
1157{
1158 return getDisplayName(daylight,style, Locale::getDefault(), result);
1159}
73c04bcf
A
1160//--------------------------------------
1161int32_t
1162TimeZone::getDSTSavings()const {
1163 if (useDaylightTime()) {
1164 return 3600000;
1165 }
1166 return 0;
1167}
1168//---------------------------------------
b75a7d8f
A
1169UnicodeString&
1170TimeZone::getDisplayName(UBool daylight, EDisplayType style, const Locale& locale, UnicodeString& result) const
1171{
1172 // SRL TODO: cache the SDF, just like java.
1173 UErrorCode status = U_ZERO_ERROR;
374ca955
A
1174#ifdef U_DEBUG_TZ
1175 char buf[128];
1176 fID.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
1177#endif
46f4442e 1178 SimpleDateFormat format(style == LONG ? ZZZZ_STR : Z_STR, locale, status);
374ca955 1179 U_DEBUG_TZ_MSG(("getDisplayName(%s)\n", buf));
b75a7d8f
A
1180 if(!U_SUCCESS(status))
1181 {
374ca955
A
1182#ifdef U_DEBUG_TZ
1183 char buf2[128];
1184 result.extract(0, sizeof(buf2)-1, buf2, sizeof(buf2), "");
1185 U_DEBUG_TZ_MSG(("getDisplayName(%s) -> %s\n", buf, buf2));
1186#endif
1187 return result.remove();
b75a7d8f
A
1188 }
1189
46f4442e
A
1190 UDate d = Calendar::getNow();
1191 int32_t rawOffset;
1192 int32_t dstOffset;
1193 this->getOffset(d, FALSE, rawOffset, dstOffset, status);
1194 if (U_FAILURE(status)) {
1195 return result.remove();
1196 }
1197
1198 if ((daylight && dstOffset != 0) || (!daylight && dstOffset == 0)) {
1199 // Current time and the request (daylight / not daylight) agree.
1200 format.setTimeZone(*this);
1201 return format.format(d, result);
1202 }
1203
b75a7d8f 1204 // Create a new SimpleTimeZone as a stand-in for this zone; the
46f4442e 1205 // stand-in will have no DST, or DST during July, but the same ID and offset,
b75a7d8f
A
1206 // and hence the same display name.
1207 // We don't cache these because they're small and cheap to create.
1208 UnicodeString tempID;
46f4442e 1209 getID(tempID);
73c04bcf 1210 SimpleTimeZone *tz = NULL;
46f4442e
A
1211 if(daylight && useDaylightTime()){
1212 // The display name for daylight saving time was requested, but currently not in DST
1213 // Set a fixed date (July 1) in this Gregorian year
1214 GregorianCalendar cal(*this, status);
1215 if (U_FAILURE(status)) {
1216 return result.remove();
1217 }
1218 cal.set(UCAL_MONTH, UCAL_JULY);
1219 cal.set(UCAL_DATE, 1);
1220
1221 // Get July 1 date
1222 d = cal.getTime(status);
1223
1224 // Check if it is in DST
1225 if (cal.get(UCAL_DST_OFFSET, status) == 0) {
1226 // We need to create a fake time zone
1227 tz = new SimpleTimeZone(rawOffset, tempID,
1228 UCAL_JUNE, 1, 0, 0,
1229 UCAL_AUGUST, 1, 0, 0,
1230 getDSTSavings(), status);
1231 if (U_FAILURE(status) || tz == NULL) {
1232 if (U_SUCCESS(status)) {
1233 status = U_MEMORY_ALLOCATION_ERROR;
1234 }
1235 return result.remove();
1236 }
1237 format.adoptTimeZone(tz);
1238 } else {
1239 format.setTimeZone(*this);
1240 }
1241 } else {
1242 // The display name for standard time was requested, but currently in DST
1243 // or display name for daylight saving time was requested, but this zone no longer
1244 // observes DST.
1245 tz = new SimpleTimeZone(rawOffset, tempID);
1246 if (U_FAILURE(status) || tz == NULL) {
1247 if (U_SUCCESS(status)) {
1248 status = U_MEMORY_ALLOCATION_ERROR;
1249 }
1250 return result.remove();
1251 }
1252 format.adoptTimeZone(tz);
1253 }
b75a7d8f 1254
46f4442e
A
1255 format.format(d, result, status);
1256 return result;
b75a7d8f
A
1257}
1258
1259
1260/**
1261 * Parse a custom time zone identifier and return a corresponding zone.
1262 * @param id a string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
1263 * GMT[+-]hh.
1264 * @return a newly created SimpleTimeZone with the given offset and
1265 * no Daylight Savings Time, or null if the id cannot be parsed.
1266*/
1267TimeZone*
1268TimeZone::createCustomTimeZone(const UnicodeString& id)
1269{
46f4442e
A
1270 int32_t sign, hour, min, sec;
1271 if (parseCustomID(id, sign, hour, min, sec)) {
1272 UnicodeString customID;
1273 formatCustomID(hour, min, sec, (sign < 0), customID);
1274 int32_t offset = sign * ((hour * 60 + min) * 60 + sec) * 1000;
1275 return new SimpleTimeZone(offset, customID);
1276 }
1277 return NULL;
1278}
1279
1280UnicodeString&
1281TimeZone::getCustomID(const UnicodeString& id, UnicodeString& normalized, UErrorCode& status) {
1282 normalized.remove();
1283 if (U_FAILURE(status)) {
1284 return normalized;
1285 }
1286 int32_t sign, hour, min, sec;
1287 if (parseCustomID(id, sign, hour, min, sec)) {
1288 formatCustomID(hour, min, sec, (sign < 0), normalized);
1289 }
1290 return normalized;
1291}
1292
1293UBool
1294TimeZone::parseCustomID(const UnicodeString& id, int32_t& sign,
1295 int32_t& hour, int32_t& min, int32_t& sec) {
b75a7d8f
A
1296 static const int32_t kParseFailed = -99999;
1297
1298 NumberFormat* numberFormat = 0;
b75a7d8f
A
1299 UnicodeString idUppercase = id;
1300 idUppercase.toUpper();
1301
1302 if (id.length() > GMT_ID_LENGTH &&
1303 idUppercase.startsWith(GMT_ID))
1304 {
1305 ParsePosition pos(GMT_ID_LENGTH);
46f4442e
A
1306 sign = 1;
1307 hour = 0;
1308 min = 0;
1309 sec = 0;
1310
1311 if (id[pos.getIndex()] == MINUS /*'-'*/) {
1312 sign = -1;
1313 } else if (id[pos.getIndex()] != PLUS /*'+'*/) {
1314 return FALSE;
1315 }
b75a7d8f
A
1316 pos.setIndex(pos.getIndex() + 1);
1317
1318 UErrorCode success = U_ZERO_ERROR;
1319 numberFormat = NumberFormat::createInstance(success);
73c04bcf 1320 if(U_FAILURE(success)){
46f4442e 1321 return FALSE;
73c04bcf 1322 }
b75a7d8f 1323 numberFormat->setParseIntegerOnly(TRUE);
46f4442e 1324 numberFormat->setParseStrict(FALSE); // TODO: Really, the default should be leninet...
b75a7d8f 1325
b75a7d8f
A
1326 // Look for either hh:mm, hhmm, or hh
1327 int32_t start = pos.getIndex();
b75a7d8f 1328 Formattable n(kParseFailed);
b75a7d8f
A
1329 numberFormat->parse(id, n, pos);
1330 if (pos.getIndex() == start) {
1331 delete numberFormat;
46f4442e 1332 return FALSE;
b75a7d8f 1333 }
46f4442e 1334 hour = n.getLong();
b75a7d8f 1335
46f4442e
A
1336 if (pos.getIndex() < id.length()) {
1337 if (pos.getIndex() - start > 2
1338 || id[pos.getIndex()] != 0x003A /*':'*/) {
1339 delete numberFormat;
1340 return FALSE;
1341 }
b75a7d8f 1342 // hh:mm
b75a7d8f
A
1343 pos.setIndex(pos.getIndex() + 1);
1344 int32_t oldPos = pos.getIndex();
1345 n.setLong(kParseFailed);
1346 numberFormat->parse(id, n, pos);
46f4442e
A
1347 if ((pos.getIndex() - oldPos) != 2) {
1348 // must be 2 digits
1349 delete numberFormat;
1350 return FALSE;
1351 }
1352 min = n.getLong();
1353 if (pos.getIndex() < id.length()) {
1354 if (id[pos.getIndex()] != 0x003A /*':'*/) {
1355 delete numberFormat;
1356 return FALSE;
1357 }
1358 // [:ss]
1359 pos.setIndex(pos.getIndex() + 1);
1360 oldPos = pos.getIndex();
1361 n.setLong(kParseFailed);
1362 numberFormat->parse(id, n, pos);
1363 if (pos.getIndex() != id.length()
1364 || (pos.getIndex() - oldPos) != 2) {
1365 delete numberFormat;
1366 return FALSE;
1367 }
1368 sec = n.getLong();
1369 }
1370 } else {
1371 // Supported formats are below -
1372 //
1373 // HHmmss
1374 // Hmmss
1375 // HHmm
1376 // Hmm
1377 // HH
1378 // H
1379
1380 int32_t length = pos.getIndex() - start;
1381 if (length <= 0 || 6 < length) {
1382 // invalid length
b75a7d8f 1383 delete numberFormat;
46f4442e
A
1384 return FALSE;
1385 }
1386 switch (length) {
1387 case 1:
1388 case 2:
1389 // already set to hour
1390 break;
1391 case 3:
1392 case 4:
1393 min = hour % 100;
1394 hour /= 100;
1395 break;
1396 case 5:
1397 case 6:
1398 sec = hour % 100;
1399 min = (hour/100) % 100;
1400 hour /= 10000;
1401 break;
b75a7d8f 1402 }
b75a7d8f 1403 }
46f4442e
A
1404
1405 delete numberFormat;
1406
1407 if (hour > kMAX_CUSTOM_HOUR || min > kMAX_CUSTOM_MIN || sec > kMAX_CUSTOM_SEC) {
1408 return FALSE;
b75a7d8f 1409 }
46f4442e
A
1410 return TRUE;
1411 }
1412 return FALSE;
1413}
b75a7d8f 1414
46f4442e
A
1415UnicodeString&
1416TimeZone::formatCustomID(int32_t hour, int32_t min, int32_t sec,
1417 UBool negative, UnicodeString& id) {
1418 // Create time zone ID - GMT[+|-]hhmm[ss]
1419 id.setTo(GMT_ID);
1420 if (hour | min | sec) {
1421 if (negative) {
1422 id += (UChar)MINUS;
1423 } else {
1424 id += (UChar)PLUS;
1425 }
b75a7d8f 1426
46f4442e
A
1427 if (hour < 10) {
1428 id += (UChar)ZERO_DIGIT;
1429 } else {
1430 id += (UChar)(ZERO_DIGIT + hour/10);
1431 }
1432 id += (UChar)(ZERO_DIGIT + hour%10);
1433
1434 if (min < 10) {
1435 id += (UChar)ZERO_DIGIT;
1436 } else {
1437 id += (UChar)(ZERO_DIGIT + min/10);
1438 }
1439 id += (UChar)(ZERO_DIGIT + min%10);
1440
1441 if (sec) {
1442 if (sec < 10) {
1443 id += (UChar)ZERO_DIGIT;
1444 } else {
1445 id += (UChar)(ZERO_DIGIT + sec/10);
1446 }
1447 id += (UChar)(ZERO_DIGIT + sec%10);
1448 }
b75a7d8f 1449 }
46f4442e 1450 return id;
b75a7d8f
A
1451}
1452
1453
1454UBool
1455TimeZone::hasSameRules(const TimeZone& other) const
1456{
1457 return (getRawOffset() == other.getRawOffset() &&
1458 useDaylightTime() == other.useDaylightTime());
1459}
1460
46f4442e
A
1461const char*
1462TimeZone::getTZDataVersion(UErrorCode& status)
1463{
1464 /* This is here to prevent race conditions. */
1465 UBool needsInit;
1466 UMTX_CHECK(&LOCK, (TZDATA_VERSION[0] == 0), needsInit);
1467 if (needsInit) {
1468 int32_t len = sizeof(TZDATA_VERSION);
1469 UResourceBundle *bundle = ures_openDirect(NULL, "zoneinfo", &status);
1470 const UChar *tzver = ures_getStringByKey(bundle, "TZVersion",
1471 &len, &status);
1472
1473 umtx_lock(&LOCK);
1474 if (U_SUCCESS(status)) {
1475 u_UCharsToChars(tzver, TZDATA_VERSION, len+1);
1476 ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
1477 }
1478 umtx_unlock(&LOCK);
1479
1480 ures_close(bundle);
1481 }
1482 if (U_FAILURE(status)) {
1483 return NULL;
1484 }
1485 return (const char*)TZDATA_VERSION;
1486}
1487
1488UnicodeString&
1489TimeZone::getCanonicalID(const UnicodeString& id, UnicodeString& canonicalID, UErrorCode& status)
1490{
1491 UBool isSystemID = FALSE;
1492 return getCanonicalID(id, canonicalID, isSystemID, status);
1493}
1494
1495UnicodeString&
1496TimeZone::getCanonicalID(const UnicodeString& id, UnicodeString& canonicalID, UBool& isSystemID,
1497 UErrorCode& status)
1498{
1499 canonicalID.remove();
1500 isSystemID = FALSE;
1501 if (U_FAILURE(status)) {
1502 return canonicalID;
1503 }
1504 ZoneMeta::getCanonicalSystemID(id, canonicalID, status);
1505 if (U_SUCCESS(status)) {
1506 isSystemID = TRUE;
1507 } else {
1508 // Not a system ID
1509 status = U_ZERO_ERROR;
1510 getCustomID(id, canonicalID, status);
1511 }
1512 return canonicalID;
1513}
1514
b75a7d8f
A
1515U_NAMESPACE_END
1516
1517#endif /* #if !UCONFIG_NO_FORMATTING */
1518
1519//eof