tests: Mark gdbus-threading test as slow
[glib.git] / glib / gtimezone.c
blobb3220dc358730d4c8d3b678c680a1b45d2a7d357
1 /*
2 * Copyright © 2010 Codethink Limited
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 * Author: Ryan Lortie <desrt@desrt.ca>
20 /* Prologue {{{1 */
22 #include "config.h"
24 #include "gtimezone.h"
26 #include <string.h>
27 #include <stdlib.h>
28 #include <signal.h>
30 #include "gmappedfile.h"
31 #include "gtestutils.h"
32 #include "gfileutils.h"
33 #include "gstrfuncs.h"
34 #include "ghash.h"
35 #include "gthread.h"
36 #include "gbytes.h"
37 #include "gslice.h"
38 #include "gdatetime.h"
39 #include "gdate.h"
41 #ifdef G_OS_WIN32
42 #define STRICT
43 #include <windows.h>
44 #endif
46 /**
47 * SECTION:timezone
48 * @title: GTimeZone
49 * @short_description: a structure representing a time zone
50 * @see_also: #GDateTime
52 * #GTimeZone is a structure that represents a time zone, at no
53 * particular point in time. It is refcounted and immutable.
55 * Each time zone has an identifier (for example, ‘Europe/London’) which is
56 * platform dependent. See g_time_zone_new() for information on the identifier
57 * formats. The identifier of a time zone can be retrieved using
58 * g_time_zone_get_identifier().
60 * A time zone contains a number of intervals. Each interval has
61 * an abbreviation to describe it (for example, ‘PDT’), an offet to UTC and a
62 * flag indicating if the daylight savings time is in effect during that
63 * interval. A time zone always has at least one interval — interval 0. Note
64 * that interval abbreviations are not the same as time zone identifiers
65 * (apart from ‘UTC’), and cannot be passed to g_time_zone_new().
67 * Every UTC time is contained within exactly one interval, but a given
68 * local time may be contained within zero, one or two intervals (due to
69 * incontinuities associated with daylight savings time).
71 * An interval may refer to a specific period of time (eg: the duration
72 * of daylight savings time during 2010) or it may refer to many periods
73 * of time that share the same properties (eg: all periods of daylight
74 * savings time). It is also possible (usually for political reasons)
75 * that some properties (like the abbreviation) change between intervals
76 * without other properties changing.
78 * #GTimeZone is available since GLib 2.26.
81 /**
82 * GTimeZone:
84 * #GTimeZone is an opaque structure whose members cannot be accessed
85 * directly.
87 * Since: 2.26
88 **/
90 /* IANA zoneinfo file format {{{1 */
92 /* unaligned */
93 typedef struct { gchar bytes[8]; } gint64_be;
94 typedef struct { gchar bytes[4]; } gint32_be;
95 typedef struct { gchar bytes[4]; } guint32_be;
97 static inline gint64 gint64_from_be (const gint64_be be) {
98 gint64 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT64_FROM_BE (tmp);
101 static inline gint32 gint32_from_be (const gint32_be be) {
102 gint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT32_FROM_BE (tmp);
105 static inline guint32 guint32_from_be (const guint32_be be) {
106 guint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GUINT32_FROM_BE (tmp);
109 /* The layout of an IANA timezone file header */
110 struct tzhead
112 gchar tzh_magic[4];
113 gchar tzh_version;
114 guchar tzh_reserved[15];
116 guint32_be tzh_ttisgmtcnt;
117 guint32_be tzh_ttisstdcnt;
118 guint32_be tzh_leapcnt;
119 guint32_be tzh_timecnt;
120 guint32_be tzh_typecnt;
121 guint32_be tzh_charcnt;
124 struct ttinfo
126 gint32_be tt_gmtoff;
127 guint8 tt_isdst;
128 guint8 tt_abbrind;
131 /* A Transition Date structure for TZ Rules, an intermediate structure
132 for parsing MSWindows and Environment-variable time zones. It
133 Generalizes MSWindows's SYSTEMTIME struct.
135 typedef struct
137 gint year;
138 gint mon;
139 gint mday;
140 gint wday;
141 gint week;
142 gint hour;
143 gint min;
144 gint sec;
145 } TimeZoneDate;
147 /* POSIX Timezone abbreviations are typically 3 or 4 characters, but
148 Microsoft uses 32-character names. We'll use one larger to ensure
149 we have room for the terminating \0.
151 #define NAME_SIZE 33
153 /* A MSWindows-style time zone transition rule. Generalizes the
154 MSWindows TIME_ZONE_INFORMATION struct. Also used to compose time
155 zones from tzset-style identifiers.
157 typedef struct
159 gint start_year;
160 gint32 std_offset;
161 gint32 dlt_offset;
162 TimeZoneDate dlt_start;
163 TimeZoneDate dlt_end;
164 gchar std_name[NAME_SIZE];
165 gchar dlt_name[NAME_SIZE];
166 } TimeZoneRule;
168 /* GTimeZone's internal representation of a Daylight Savings (Summer)
169 time interval.
171 typedef struct
173 gint32 gmt_offset;
174 gboolean is_dst;
175 gchar *abbrev;
176 } TransitionInfo;
178 /* GTimeZone's representation of a transition time to or from Daylight
179 Savings (Summer) time and Standard time for the zone. */
180 typedef struct
182 gint64 time;
183 gint info_index;
184 } Transition;
186 /* GTimeZone structure */
187 struct _GTimeZone
189 gchar *name;
190 GArray *t_info; /* Array of TransitionInfo */
191 GArray *transitions; /* Array of Transition */
192 gint ref_count;
195 G_LOCK_DEFINE_STATIC (time_zones);
196 static GHashTable/*<string?, GTimeZone>*/ *time_zones;
198 #define MIN_TZYEAR 1916 /* Daylight Savings started in WWI */
199 #define MAX_TZYEAR 2999 /* And it's not likely ever to go away, but
200 there's no point in getting carried
201 away. */
204 * g_time_zone_unref:
205 * @tz: a #GTimeZone
207 * Decreases the reference count on @tz.
209 * Since: 2.26
211 void
212 g_time_zone_unref (GTimeZone *tz)
214 int ref_count;
216 again:
217 ref_count = g_atomic_int_get (&tz->ref_count);
219 g_assert (ref_count > 0);
221 if (ref_count == 1)
223 if (tz->name != NULL)
225 G_LOCK(time_zones);
227 /* someone else might have grabbed a ref in the meantime */
228 if G_UNLIKELY (g_atomic_int_get (&tz->ref_count) != 1)
230 G_UNLOCK(time_zones);
231 goto again;
234 g_hash_table_remove (time_zones, tz->name);
235 G_UNLOCK(time_zones);
238 if (tz->t_info != NULL)
240 gint idx;
241 for (idx = 0; idx < tz->t_info->len; idx++)
243 TransitionInfo *info = &g_array_index (tz->t_info, TransitionInfo, idx);
244 g_free (info->abbrev);
246 g_array_free (tz->t_info, TRUE);
248 if (tz->transitions != NULL)
249 g_array_free (tz->transitions, TRUE);
250 g_free (tz->name);
252 g_slice_free (GTimeZone, tz);
255 else if G_UNLIKELY (!g_atomic_int_compare_and_exchange (&tz->ref_count,
256 ref_count,
257 ref_count - 1))
258 goto again;
262 * g_time_zone_ref:
263 * @tz: a #GTimeZone
265 * Increases the reference count on @tz.
267 * Returns: a new reference to @tz.
269 * Since: 2.26
271 GTimeZone *
272 g_time_zone_ref (GTimeZone *tz)
274 g_assert (tz->ref_count > 0);
276 g_atomic_int_inc (&tz->ref_count);
278 return tz;
281 /* fake zoneinfo creation (for RFC3339/ISO 8601 timezones) {{{1 */
283 * parses strings of the form h or hh[[:]mm[[[:]ss]]] where:
284 * - h[h] is 0 to 23
285 * - mm is 00 to 59
286 * - ss is 00 to 59
288 static gboolean
289 parse_time (const gchar *time_,
290 gint32 *offset)
292 if (*time_ < '0' || '9' < *time_)
293 return FALSE;
295 *offset = 60 * 60 * (*time_++ - '0');
297 if (*time_ == '\0')
298 return TRUE;
300 if (*time_ != ':')
302 if (*time_ < '0' || '9' < *time_)
303 return FALSE;
305 *offset *= 10;
306 *offset += 60 * 60 * (*time_++ - '0');
308 if (*offset > 23 * 60 * 60)
309 return FALSE;
311 if (*time_ == '\0')
312 return TRUE;
315 if (*time_ == ':')
316 time_++;
318 if (*time_ < '0' || '5' < *time_)
319 return FALSE;
321 *offset += 10 * 60 * (*time_++ - '0');
323 if (*time_ < '0' || '9' < *time_)
324 return FALSE;
326 *offset += 60 * (*time_++ - '0');
328 if (*time_ == '\0')
329 return TRUE;
331 if (*time_ == ':')
332 time_++;
334 if (*time_ < '0' || '5' < *time_)
335 return FALSE;
337 *offset += 10 * (*time_++ - '0');
339 if (*time_ < '0' || '9' < *time_)
340 return FALSE;
342 *offset += *time_++ - '0';
344 return *time_ == '\0';
347 static gboolean
348 parse_constant_offset (const gchar *name,
349 gint32 *offset)
351 if (g_strcmp0 (name, "UTC") == 0)
353 *offset = 0;
354 return TRUE;
357 if (*name >= '0' && '9' >= *name)
358 return parse_time (name, offset);
360 switch (*name++)
362 case 'Z':
363 *offset = 0;
364 return !*name;
366 case '+':
367 return parse_time (name, offset);
369 case '-':
370 if (parse_time (name, offset))
372 *offset = -*offset;
373 return TRUE;
376 default:
377 return FALSE;
381 static void
382 zone_for_constant_offset (GTimeZone *gtz, const gchar *name)
384 gint32 offset;
385 TransitionInfo info;
387 if (name == NULL || !parse_constant_offset (name, &offset))
388 return;
390 info.gmt_offset = offset;
391 info.is_dst = FALSE;
392 info.abbrev = g_strdup (name);
394 gtz->name = g_strdup (name);
395 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), 1);
396 g_array_append_val (gtz->t_info, info);
398 /* Constant offset, no transitions */
399 gtz->transitions = NULL;
402 #ifdef G_OS_UNIX
403 static GBytes*
404 zone_info_unix (const gchar *identifier,
405 gchar **out_identifier)
407 gchar *filename;
408 GMappedFile *file = NULL;
409 GBytes *zoneinfo = NULL;
410 gchar *resolved_identifier = NULL;
411 const gchar *tzdir;
413 tzdir = getenv ("TZDIR");
414 if (tzdir == NULL)
415 tzdir = "/usr/share/zoneinfo";
417 /* identifier can be a relative or absolute path name;
418 if relative, it is interpreted starting from /usr/share/zoneinfo
419 while the POSIX standard says it should start with :,
420 glibc allows both syntaxes, so we should too */
421 if (identifier != NULL)
423 resolved_identifier = g_strdup (identifier);
425 if (*identifier == ':')
426 identifier ++;
428 if (g_path_is_absolute (identifier))
429 filename = g_strdup (identifier);
430 else
431 filename = g_build_filename (tzdir, identifier, NULL);
433 else
435 gsize prefix_len = 0;
436 gchar *canonical_path = NULL;
437 GError *read_link_err = NULL;
439 filename = g_strdup ("/etc/localtime");
441 /* Resolve the actual timezone pointed to by /etc/localtime. */
442 resolved_identifier = g_file_read_link (filename, &read_link_err);
443 if (resolved_identifier == NULL)
445 gboolean not_a_symlink = g_error_matches (read_link_err,
446 G_FILE_ERROR,
447 G_FILE_ERROR_INVAL);
448 g_clear_error (&read_link_err);
450 /* Fallback to the content of /var/db/zoneinfo if /etc/localtime is
451 * not a symlink. This is where 'tzsetup' program on FreeBSD and
452 * DragonflyBSD stores the timezone chosen by the user. */
453 if (not_a_symlink && g_file_get_contents ("/var/db/zoneinfo",
454 &resolved_identifier,
455 NULL, NULL))
456 g_strchomp (resolved_identifier);
457 else
459 /* Error */
460 g_assert (resolved_identifier == NULL);
461 goto out;
464 else
466 /* Resolve relative path */
467 canonical_path = g_canonicalize_filename (resolved_identifier, "/etc");
468 g_free (resolved_identifier);
469 resolved_identifier = g_steal_pointer (&canonical_path);
472 /* Strip the prefix and slashes if possible. */
473 if (g_str_has_prefix (resolved_identifier, tzdir))
475 prefix_len = strlen (tzdir);
476 while (*(resolved_identifier + prefix_len) == '/')
477 prefix_len++;
480 if (prefix_len > 0)
481 memmove (resolved_identifier, resolved_identifier + prefix_len,
482 strlen (resolved_identifier) - prefix_len + 1 /* nul terminator */);
484 g_free (canonical_path);
487 file = g_mapped_file_new (filename, FALSE, NULL);
488 if (file != NULL)
490 zoneinfo = g_bytes_new_with_free_func (g_mapped_file_get_contents (file),
491 g_mapped_file_get_length (file),
492 (GDestroyNotify)g_mapped_file_unref,
493 g_mapped_file_ref (file));
494 g_mapped_file_unref (file);
497 g_assert (resolved_identifier != NULL);
499 out:
500 if (out_identifier != NULL)
501 *out_identifier = g_steal_pointer (&resolved_identifier);
503 g_free (resolved_identifier);
504 g_free (filename);
506 return zoneinfo;
509 static void
510 init_zone_from_iana_info (GTimeZone *gtz,
511 GBytes *zoneinfo,
512 gchar *identifier /* (transfer full) */)
514 gsize size;
515 guint index;
516 guint32 time_count, type_count;
517 guint8 *tz_transitions, *tz_type_index, *tz_ttinfo;
518 guint8 *tz_abbrs;
519 gsize timesize = sizeof (gint32);
520 const struct tzhead *header = g_bytes_get_data (zoneinfo, &size);
522 g_return_if_fail (size >= sizeof (struct tzhead) &&
523 memcmp (header, "TZif", 4) == 0);
525 if (header->tzh_version == '2')
527 /* Skip ahead to the newer 64-bit data if it's available. */
528 header = (const struct tzhead *)
529 (((const gchar *) (header + 1)) +
530 guint32_from_be(header->tzh_ttisgmtcnt) +
531 guint32_from_be(header->tzh_ttisstdcnt) +
532 8 * guint32_from_be(header->tzh_leapcnt) +
533 5 * guint32_from_be(header->tzh_timecnt) +
534 6 * guint32_from_be(header->tzh_typecnt) +
535 guint32_from_be(header->tzh_charcnt));
536 timesize = sizeof (gint64);
538 time_count = guint32_from_be(header->tzh_timecnt);
539 type_count = guint32_from_be(header->tzh_typecnt);
541 tz_transitions = ((guint8 *) (header) + sizeof (*header));
542 tz_type_index = tz_transitions + timesize * time_count;
543 tz_ttinfo = tz_type_index + time_count;
544 tz_abbrs = tz_ttinfo + sizeof (struct ttinfo) * type_count;
546 gtz->name = g_steal_pointer (&identifier);
547 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo),
548 type_count);
549 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition),
550 time_count);
552 for (index = 0; index < type_count; index++)
554 TransitionInfo t_info;
555 struct ttinfo info = ((struct ttinfo*)tz_ttinfo)[index];
556 t_info.gmt_offset = gint32_from_be (info.tt_gmtoff);
557 t_info.is_dst = info.tt_isdst ? TRUE : FALSE;
558 t_info.abbrev = g_strdup ((gchar *) &tz_abbrs[info.tt_abbrind]);
559 g_array_append_val (gtz->t_info, t_info);
562 for (index = 0; index < time_count; index++)
564 Transition trans;
565 if (header->tzh_version == '2')
566 trans.time = gint64_from_be (((gint64_be*)tz_transitions)[index]);
567 else
568 trans.time = gint32_from_be (((gint32_be*)tz_transitions)[index]);
569 trans.info_index = tz_type_index[index];
570 g_assert (trans.info_index >= 0);
571 g_assert (trans.info_index < gtz->t_info->len);
572 g_array_append_val (gtz->transitions, trans);
576 #elif defined (G_OS_WIN32)
578 static void
579 copy_windows_systemtime (SYSTEMTIME *s_time, TimeZoneDate *tzdate)
581 tzdate->sec = s_time->wSecond;
582 tzdate->min = s_time->wMinute;
583 tzdate->hour = s_time->wHour;
584 tzdate->mon = s_time->wMonth;
585 tzdate->year = s_time->wYear;
586 tzdate->wday = s_time->wDayOfWeek ? s_time->wDayOfWeek : 7;
588 if (s_time->wYear)
590 tzdate->mday = s_time->wDay;
591 tzdate->wday = 0;
593 else
594 tzdate->week = s_time->wDay;
597 /* UTC = local time + bias while local time = UTC + offset */
598 static void
599 rule_from_windows_time_zone_info (TimeZoneRule *rule,
600 TIME_ZONE_INFORMATION *tzi)
602 /* Set offset */
603 if (tzi->StandardDate.wMonth)
605 rule->std_offset = -(tzi->Bias + tzi->StandardBias) * 60;
606 rule->dlt_offset = -(tzi->Bias + tzi->DaylightBias) * 60;
607 copy_windows_systemtime (&(tzi->DaylightDate), &(rule->dlt_start));
609 copy_windows_systemtime (&(tzi->StandardDate), &(rule->dlt_end));
613 else
615 rule->std_offset = -tzi->Bias * 60;
616 rule->dlt_start.mon = 0;
618 strncpy (rule->std_name, (gchar*)tzi->StandardName, NAME_SIZE - 1);
619 strncpy (rule->dlt_name, (gchar*)tzi->DaylightName, NAME_SIZE - 1);
622 static gchar*
623 windows_default_tzname (void)
625 const gchar *subkey =
626 "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation";
627 HKEY key;
628 gchar *key_name = NULL;
629 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
630 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
632 DWORD size = 0;
633 if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
634 NULL, &size) == ERROR_SUCCESS)
636 key_name = g_malloc ((gint)size);
637 if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
638 (LPBYTE)key_name, &size) != ERROR_SUCCESS)
640 g_free (key_name);
641 key_name = NULL;
644 RegCloseKey (key);
646 return key_name;
649 typedef struct
651 LONG Bias;
652 LONG StandardBias;
653 LONG DaylightBias;
654 SYSTEMTIME StandardDate;
655 SYSTEMTIME DaylightDate;
656 } RegTZI;
658 static void
659 system_time_copy (SYSTEMTIME *orig, SYSTEMTIME *target)
661 g_return_if_fail (orig != NULL);
662 g_return_if_fail (target != NULL);
664 target->wYear = orig->wYear;
665 target->wMonth = orig->wMonth;
666 target->wDayOfWeek = orig->wDayOfWeek;
667 target->wDay = orig->wDay;
668 target->wHour = orig->wHour;
669 target->wMinute = orig->wMinute;
670 target->wSecond = orig->wSecond;
671 target->wMilliseconds = orig->wMilliseconds;
674 static void
675 register_tzi_to_tzi (RegTZI *reg, TIME_ZONE_INFORMATION *tzi)
677 g_return_if_fail (reg != NULL);
678 g_return_if_fail (tzi != NULL);
679 tzi->Bias = reg->Bias;
680 system_time_copy (&(reg->StandardDate), &(tzi->StandardDate));
681 tzi->StandardBias = reg->StandardBias;
682 system_time_copy (&(reg->DaylightDate), &(tzi->DaylightDate));
683 tzi->DaylightBias = reg->DaylightBias;
686 static gint
687 rules_from_windows_time_zone (const gchar *identifier,
688 gchar **out_identifier,
689 TimeZoneRule **rules)
691 HKEY key;
692 gchar *subkey, *subkey_dynamic;
693 gchar *key_name = NULL;
694 const gchar *reg_key =
695 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\";
696 TIME_ZONE_INFORMATION tzi;
697 DWORD size;
698 gint rules_num = 0;
699 RegTZI regtzi, regtzi_prev;
701 g_assert (out_identifier != NULL);
702 g_assert (rules != NULL);
704 *out_identifier = NULL;
705 *rules = NULL;
706 key_name = NULL;
708 if (!identifier)
709 key_name = windows_default_tzname ();
710 else
711 key_name = g_strdup (identifier);
713 if (!key_name)
714 return 0;
716 subkey = g_strconcat (reg_key, key_name, NULL);
717 subkey_dynamic = g_strconcat (subkey, "\\Dynamic DST", NULL);
719 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
720 KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
721 return 0;
722 size = sizeof tzi.StandardName;
723 if (RegQueryValueExA (key, "Std", NULL, NULL,
724 (LPBYTE)&(tzi.StandardName), &size) != ERROR_SUCCESS)
725 goto failed;
727 size = sizeof tzi.DaylightName;
729 if (RegQueryValueExA (key, "Dlt", NULL, NULL,
730 (LPBYTE)&(tzi.DaylightName), &size) != ERROR_SUCCESS)
731 goto failed;
733 RegCloseKey (key);
734 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey_dynamic, 0,
735 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
737 DWORD first, last;
738 int year, i;
739 gchar *s;
741 size = sizeof first;
742 if (RegQueryValueExA (key, "FirstEntry", NULL, NULL,
743 (LPBYTE) &first, &size) != ERROR_SUCCESS)
744 goto failed;
746 size = sizeof last;
747 if (RegQueryValueExA (key, "LastEntry", NULL, NULL,
748 (LPBYTE) &last, &size) != ERROR_SUCCESS)
749 goto failed;
751 rules_num = last - first + 2;
752 *rules = g_new0 (TimeZoneRule, rules_num);
754 for (year = first, i = 0; year <= last; year++)
756 s = g_strdup_printf ("%d", year);
758 size = sizeof regtzi;
759 if (RegQueryValueExA (key, s, NULL, NULL,
760 (LPBYTE) &regtzi, &size) != ERROR_SUCCESS)
762 g_free (*rules);
763 *rules = NULL;
764 break;
767 g_free (s);
769 if (year > first && memcmp (&regtzi_prev, &regtzi, sizeof regtzi) == 0)
770 continue;
771 else
772 memcpy (&regtzi_prev, &regtzi, sizeof regtzi);
774 register_tzi_to_tzi (&regtzi, &tzi);
775 rule_from_windows_time_zone_info (&(*rules)[i], &tzi);
776 (*rules)[i++].start_year = year;
779 rules_num = i + 1;
781 failed:
782 RegCloseKey (key);
784 else if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
785 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
787 size = sizeof regtzi;
788 if (RegQueryValueExA (key, "TZI", NULL, NULL,
789 (LPBYTE) &regtzi, &size) == ERROR_SUCCESS)
791 rules_num = 2;
792 *rules = g_new0 (TimeZoneRule, 2);
793 register_tzi_to_tzi (&regtzi, &tzi);
794 rule_from_windows_time_zone_info (&(*rules)[0], &tzi);
797 RegCloseKey (key);
800 g_free (subkey_dynamic);
801 g_free (subkey);
803 if (*rules)
805 (*rules)[0].start_year = MIN_TZYEAR;
806 if ((*rules)[rules_num - 2].start_year < MAX_TZYEAR)
807 (*rules)[rules_num - 1].start_year = MAX_TZYEAR;
808 else
809 (*rules)[rules_num - 1].start_year = (*rules)[rules_num - 2].start_year + 1;
811 *out_identifier = g_steal_pointer (&key_name);
813 return rules_num;
816 g_free (key_name);
818 return 0;
821 #endif
823 static void
824 find_relative_date (TimeZoneDate *buffer)
826 gint wday;
827 GDate date;
828 g_date_clear (&date, 1);
829 wday = buffer->wday;
831 /* Get last day if last is needed, first day otherwise */
832 if (buffer->mon == 13 || buffer->mon == 14) /* Julian Date */
834 g_date_set_dmy (&date, 1, 1, buffer->year);
835 if (wday >= 59 && buffer->mon == 13 && g_date_is_leap_year (buffer->year))
836 g_date_add_days (&date, wday);
837 else
838 g_date_add_days (&date, wday - 1);
839 buffer->mon = (int) g_date_get_month (&date);
840 buffer->mday = (int) g_date_get_day (&date);
841 buffer->wday = 0;
843 else /* M.W.D */
845 guint days;
846 guint days_in_month = g_date_days_in_month (buffer->mon, buffer->year);
847 GDateWeekday first_wday;
849 g_date_set_dmy (&date, 1, buffer->mon, buffer->year);
850 first_wday = g_date_get_weekday (&date);
852 if (first_wday > wday)
853 ++(buffer->week);
854 /* week is 1 <= w <= 5, we need 0-based */
855 days = 7 * (buffer->week - 1) + wday - first_wday;
857 while (days > days_in_month)
858 days -= 7;
860 g_date_add_days (&date, days);
862 buffer->mday = g_date_get_day (&date);
866 /* Offset is previous offset of local time. Returns 0 if month is 0 */
867 static gint64
868 boundary_for_year (TimeZoneDate *boundary,
869 gint year,
870 gint32 offset)
872 TimeZoneDate buffer;
873 GDate date;
874 const guint64 unix_epoch_start = 719163L;
875 const guint64 seconds_per_day = 86400L;
877 if (!boundary->mon)
878 return 0;
879 buffer = *boundary;
881 if (boundary->year == 0)
883 buffer.year = year;
885 if (buffer.wday)
886 find_relative_date (&buffer);
889 g_assert (buffer.year == year);
890 g_date_clear (&date, 1);
891 g_date_set_dmy (&date, buffer.mday, buffer.mon, buffer.year);
892 return ((g_date_get_julian (&date) - unix_epoch_start) * seconds_per_day +
893 buffer.hour * 3600 + buffer.min * 60 + buffer.sec - offset);
896 static void
897 fill_transition_info_from_rule (TransitionInfo *info,
898 TimeZoneRule *rule,
899 gboolean is_dst)
901 gint offset = is_dst ? rule->dlt_offset : rule->std_offset;
902 gchar *name = is_dst ? rule->dlt_name : rule->std_name;
904 info->gmt_offset = offset;
905 info->is_dst = is_dst;
907 if (name)
908 info->abbrev = g_strdup (name);
910 else
911 info->abbrev = g_strdup_printf ("%+03d%02d",
912 (int) offset / 3600,
913 (int) abs (offset / 60) % 60);
916 static void
917 init_zone_from_rules (GTimeZone *gtz,
918 TimeZoneRule *rules,
919 gint rules_num,
920 gchar *identifier /* (transfer full) */)
922 guint type_count = 0, trans_count = 0, info_index = 0;
923 guint ri; /* rule index */
924 gboolean skip_first_std_trans = TRUE;
925 gint32 last_offset;
927 type_count = 0;
928 trans_count = 0;
930 /* Last rule only contains max year */
931 for (ri = 0; ri < rules_num - 1; ri++)
933 if (rules[ri].dlt_start.mon || rules[ri].dlt_end.mon)
935 guint rulespan = (rules[ri + 1].start_year - rules[ri].start_year);
936 guint transitions = rules[ri].dlt_start.mon > 0 ? 1 : 0;
937 transitions += rules[ri].dlt_end.mon > 0 ? 1 : 0;
938 type_count += rules[ri].dlt_start.mon > 0 ? 2 : 1;
939 trans_count += transitions * rulespan;
941 else
942 type_count++;
945 gtz->name = g_steal_pointer (&identifier);
946 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), type_count);
947 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition), trans_count);
949 last_offset = rules[0].std_offset;
951 for (ri = 0; ri < rules_num - 1; ri++)
953 if ((rules[ri].std_offset || rules[ri].dlt_offset) &&
954 rules[ri].dlt_start.mon == 0 && rules[ri].dlt_end.mon == 0)
956 TransitionInfo std_info;
957 /* Standard */
958 fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
959 g_array_append_val (gtz->t_info, std_info);
961 if (ri > 0 &&
962 ((rules[ri - 1].dlt_start.mon > 12 &&
963 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
964 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
966 /* The previous rule was a southern hemisphere rule that
967 starts the year with DST, so we need to add a
968 transition to return to standard time */
969 guint year = rules[ri].start_year;
970 gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
971 year, last_offset);
972 Transition std_trans = {std_time, info_index};
973 g_array_append_val (gtz->transitions, std_trans);
976 last_offset = rules[ri].std_offset;
977 ++info_index;
978 skip_first_std_trans = TRUE;
980 else
982 const guint start_year = rules[ri].start_year;
983 const guint end_year = rules[ri + 1].start_year;
984 gboolean dlt_first;
985 guint year;
986 TransitionInfo std_info, dlt_info;
987 if (rules[ri].dlt_start.mon > 12)
988 dlt_first = rules[ri].dlt_start.wday > rules[ri].dlt_end.wday;
989 else
990 dlt_first = rules[ri].dlt_start.mon > rules[ri].dlt_end.mon;
991 /* Standard rules are always even, because before the first
992 transition is always standard time, and 0 is even. */
993 fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
994 fill_transition_info_from_rule (&dlt_info, &(rules[ri]), TRUE);
996 g_array_append_val (gtz->t_info, std_info);
997 g_array_append_val (gtz->t_info, dlt_info);
999 /* Transition dates. We hope that a year which ends daylight
1000 time in a southern-hemisphere country (i.e., one that
1001 begins the year in daylight time) will include a rule
1002 which has only a dlt_end. */
1003 for (year = start_year; year < end_year; year++)
1005 gint32 dlt_offset = (dlt_first ? last_offset :
1006 rules[ri].dlt_offset);
1007 gint32 std_offset = (dlt_first ? rules[ri].std_offset :
1008 last_offset);
1009 /* NB: boundary_for_year returns 0 if mon == 0 */
1010 gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
1011 year, dlt_offset);
1012 gint64 dlt_time = boundary_for_year (&rules[ri].dlt_start,
1013 year, std_offset);
1014 Transition std_trans = {std_time, info_index};
1015 Transition dlt_trans = {dlt_time, info_index + 1};
1016 last_offset = (dlt_first ? rules[ri].dlt_offset :
1017 rules[ri].std_offset);
1018 if (dlt_first)
1020 if (skip_first_std_trans)
1021 skip_first_std_trans = FALSE;
1022 else if (std_time)
1023 g_array_append_val (gtz->transitions, std_trans);
1024 if (dlt_time)
1025 g_array_append_val (gtz->transitions, dlt_trans);
1027 else
1029 if (dlt_time)
1030 g_array_append_val (gtz->transitions, dlt_trans);
1031 if (std_time)
1032 g_array_append_val (gtz->transitions, std_trans);
1036 info_index += 2;
1039 if (ri > 0 &&
1040 ((rules[ri - 1].dlt_start.mon > 12 &&
1041 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
1042 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
1044 /* The previous rule was a southern hemisphere rule that
1045 starts the year with DST, so we need to add a
1046 transition to return to standard time */
1047 TransitionInfo info;
1048 guint year = rules[ri].start_year;
1049 Transition trans;
1050 fill_transition_info_from_rule (&info, &(rules[ri - 1]), FALSE);
1051 g_array_append_val (gtz->t_info, info);
1052 trans.time = boundary_for_year (&rules[ri - 1].dlt_end,
1053 year, last_offset);
1054 trans.info_index = info_index;
1055 g_array_append_val (gtz->transitions, trans);
1060 * parses date[/time] for parsing TZ environment variable
1062 * date is either Mm.w.d, Jn or N
1063 * - m is 1 to 12
1064 * - w is 1 to 5
1065 * - d is 0 to 6
1066 * - n is 1 to 365
1067 * - N is 0 to 365
1069 * time is either h or hh[[:]mm[[[:]ss]]]
1070 * - h[h] is 0 to 23
1071 * - mm is 00 to 59
1072 * - ss is 00 to 59
1074 static gboolean
1075 parse_mwd_boundary (gchar **pos, TimeZoneDate *boundary)
1077 gint month, week, day;
1079 if (**pos == '\0' || **pos < '0' || '9' < **pos)
1080 return FALSE;
1082 month = *(*pos)++ - '0';
1084 if ((month == 1 && **pos >= '0' && '2' >= **pos) ||
1085 (month == 0 && **pos >= '0' && '9' >= **pos))
1087 month *= 10;
1088 month += *(*pos)++ - '0';
1091 if (*(*pos)++ != '.' || month == 0)
1092 return FALSE;
1094 if (**pos == '\0' || **pos < '1' || '5' < **pos)
1095 return FALSE;
1097 week = *(*pos)++ - '0';
1099 if (*(*pos)++ != '.')
1100 return FALSE;
1102 if (**pos == '\0' || **pos < '0' || '6' < **pos)
1103 return FALSE;
1105 day = *(*pos)++ - '0';
1107 if (!day)
1108 day += 7;
1110 boundary->year = 0;
1111 boundary->mon = month;
1112 boundary->week = week;
1113 boundary->wday = day;
1114 return TRUE;
1117 /* Different implementations of tzset interpret the Julian day field
1118 differently. For example, Linux specifies that it should be 1-based
1119 (1 Jan is JD 1) for both Jn and n formats, while zOS and BSD
1120 specify that a Jn JD is 1-based while an n JD is 0-based. Rather
1121 than trying to follow different specs, we will follow GDate's
1122 practice thatIn order to keep it simple, we will follow Linux's
1123 practice. */
1125 static gboolean
1126 parse_julian_boundary (gchar** pos, TimeZoneDate *boundary,
1127 gboolean ignore_leap)
1129 gint day = 0;
1130 GDate date;
1132 while (**pos >= '0' && '9' >= **pos)
1134 day *= 10;
1135 day += *(*pos)++ - '0';
1138 if (day < 1 || 365 < day)
1139 return FALSE;
1141 g_date_clear (&date, 1);
1142 g_date_set_julian (&date, day);
1143 boundary->year = 0;
1144 boundary->mon = (int) g_date_get_month (&date);
1145 boundary->mday = (int) g_date_get_day (&date);
1146 boundary->wday = 0;
1148 if (!ignore_leap && day >= 59)
1149 boundary->mday++;
1151 return TRUE;
1154 static gboolean
1155 parse_tz_boundary (const gchar *identifier,
1156 TimeZoneDate *boundary)
1158 gchar *pos;
1160 pos = (gchar*)identifier;
1161 /* Month-week-weekday */
1162 if (*pos == 'M')
1164 ++pos;
1165 if (!parse_mwd_boundary (&pos, boundary))
1166 return FALSE;
1168 /* Julian date which ignores Feb 29 in leap years */
1169 else if (*pos == 'J')
1171 ++pos;
1172 if (!parse_julian_boundary (&pos, boundary, FALSE))
1173 return FALSE ;
1175 /* Julian date which counts Feb 29 in leap years */
1176 else if (*pos >= '0' && '9' >= *pos)
1178 if (!parse_julian_boundary (&pos, boundary, TRUE))
1179 return FALSE;
1181 else
1182 return FALSE;
1184 /* Time */
1186 if (*pos == '/')
1188 gint32 offset;
1190 if (!parse_time (++pos, &offset))
1191 return FALSE;
1193 boundary->hour = offset / 3600;
1194 boundary->min = (offset / 60) % 60;
1195 boundary->sec = offset % 3600;
1197 return TRUE;
1200 else
1202 boundary->hour = 2;
1203 boundary->min = 0;
1204 boundary->sec = 0;
1206 return *pos == '\0';
1210 static gint
1211 create_ruleset_from_rule (TimeZoneRule **rules, TimeZoneRule *rule)
1213 *rules = g_new0 (TimeZoneRule, 2);
1215 (*rules)[0].start_year = MIN_TZYEAR;
1216 (*rules)[1].start_year = MAX_TZYEAR;
1218 (*rules)[0].std_offset = -rule->std_offset;
1219 (*rules)[0].dlt_offset = -rule->dlt_offset;
1220 (*rules)[0].dlt_start = rule->dlt_start;
1221 (*rules)[0].dlt_end = rule->dlt_end;
1222 strcpy ((*rules)[0].std_name, rule->std_name);
1223 strcpy ((*rules)[0].dlt_name, rule->dlt_name);
1224 return 2;
1227 static gboolean
1228 parse_offset (gchar **pos, gint32 *target)
1230 gchar *buffer;
1231 gchar *target_pos = *pos;
1232 gboolean ret;
1234 while (**pos == '+' || **pos == '-' || **pos == ':' ||
1235 (**pos >= '0' && '9' >= **pos))
1236 ++(*pos);
1238 buffer = g_strndup (target_pos, *pos - target_pos);
1239 ret = parse_constant_offset (buffer, target);
1240 g_free (buffer);
1242 return ret;
1245 static gboolean
1246 parse_identifier_boundary (gchar **pos, TimeZoneDate *target)
1248 gchar *buffer;
1249 gchar *target_pos = *pos;
1250 gboolean ret;
1252 while (**pos != ',' && **pos != '\0')
1253 ++(*pos);
1254 buffer = g_strndup (target_pos, *pos - target_pos);
1255 ret = parse_tz_boundary (buffer, target);
1256 g_free (buffer);
1258 return ret;
1261 static gboolean
1262 set_tz_name (gchar **pos, gchar *buffer, guint size)
1264 gchar *name_pos = *pos;
1265 guint len;
1267 /* Name is ASCII alpha (Is this necessarily true?) */
1268 while (g_ascii_isalpha (**pos))
1269 ++(*pos);
1271 /* Name should be three or more alphabetic characters */
1272 if (*pos - name_pos < 3)
1273 return FALSE;
1275 memset (buffer, 0, NAME_SIZE);
1276 /* name_pos isn't 0-terminated, so we have to limit the length expressly */
1277 len = *pos - name_pos > size - 1 ? size - 1 : *pos - name_pos;
1278 strncpy (buffer, name_pos, len);
1279 return TRUE;
1282 static gboolean
1283 parse_identifier_boundaries (gchar **pos, TimeZoneRule *tzr)
1285 if (*(*pos)++ != ',')
1286 return FALSE;
1288 /* Start date */
1289 if (!parse_identifier_boundary (pos, &(tzr->dlt_start)) || *(*pos)++ != ',')
1290 return FALSE;
1292 /* End date */
1293 if (!parse_identifier_boundary (pos, &(tzr->dlt_end)))
1294 return FALSE;
1295 return TRUE;
1299 * Creates an array of TimeZoneRule from a TZ environment variable
1300 * type of identifier. Should free rules afterwards
1302 static gint
1303 rules_from_identifier (const gchar *identifier,
1304 gchar **out_identifier,
1305 TimeZoneRule **rules)
1307 gchar *pos;
1308 TimeZoneRule tzr;
1310 g_assert (out_identifier != NULL);
1311 g_assert (rules != NULL);
1313 *out_identifier = NULL;
1314 *rules = NULL;
1316 if (!identifier)
1317 return 0;
1319 pos = (gchar*)identifier;
1320 memset (&tzr, 0, sizeof (tzr));
1321 /* Standard offset */
1322 if (!(set_tz_name (&pos, tzr.std_name, NAME_SIZE)) ||
1323 !parse_offset (&pos, &(tzr.std_offset)))
1324 return 0;
1326 if (*pos == 0)
1328 *out_identifier = g_strdup (identifier);
1329 return create_ruleset_from_rule (rules, &tzr);
1332 /* Format 2 */
1333 if (!(set_tz_name (&pos, tzr.dlt_name, NAME_SIZE)))
1334 return 0;
1335 parse_offset (&pos, &(tzr.dlt_offset));
1336 if (tzr.dlt_offset == 0) /* No daylight offset given, assume it's 1
1337 hour earlier that standard */
1338 tzr.dlt_offset = tzr.std_offset - 3600;
1339 if (*pos == '\0')
1340 #ifdef G_OS_WIN32
1341 /* Windows allows us to use the US DST boundaries if they're not given */
1343 int i;
1344 guint rules_num = 0;
1346 /* Use US rules, Windows' default is Pacific Standard Time */
1347 if ((rules_num = rules_from_windows_time_zone ("Pacific Standard Time",
1348 out_identifier,
1349 rules)))
1351 for (i = 0; i < rules_num - 1; i++)
1353 (*rules)[i].std_offset = - tzr.std_offset;
1354 (*rules)[i].dlt_offset = - tzr.dlt_offset;
1355 strcpy ((*rules)[i].std_name, tzr.std_name);
1356 strcpy ((*rules)[i].dlt_name, tzr.dlt_name);
1359 return rules_num;
1361 else
1362 return 0;
1364 #else
1365 return 0;
1366 #endif
1367 /* Start and end required (format 2) */
1368 if (!parse_identifier_boundaries (&pos, &tzr))
1369 return 0;
1371 *out_identifier = g_strdup (identifier);
1372 return create_ruleset_from_rule (rules, &tzr);
1375 /* Construction {{{1 */
1377 * g_time_zone_new:
1378 * @identifier: (nullable): a timezone identifier
1380 * Creates a #GTimeZone corresponding to @identifier.
1382 * @identifier can either be an RFC3339/ISO 8601 time offset or
1383 * something that would pass as a valid value for the `TZ` environment
1384 * variable (including %NULL).
1386 * In Windows, @identifier can also be the unlocalized name of a time
1387 * zone for standard time, for example "Pacific Standard Time".
1389 * Valid RFC3339 time offsets are `"Z"` (for UTC) or
1390 * `"±hh:mm"`. ISO 8601 additionally specifies
1391 * `"±hhmm"` and `"±hh"`. Offsets are
1392 * time values to be added to Coordinated Universal Time (UTC) to get
1393 * the local time.
1395 * In UNIX, the `TZ` environment variable typically corresponds
1396 * to the name of a file in the zoneinfo database, or string in
1397 * "std offset [dst [offset],start[/time],end[/time]]" (POSIX) format.
1398 * There are no spaces in the specification. The name of standard
1399 * and daylight savings time zone must be three or more alphabetic
1400 * characters. Offsets are time values to be added to local time to
1401 * get Coordinated Universal Time (UTC) and should be
1402 * `"[±]hh[[:]mm[:ss]]"`. Dates are either
1403 * `"Jn"` (Julian day with n between 1 and 365, leap
1404 * years not counted), `"n"` (zero-based Julian day
1405 * with n between 0 and 365) or `"Mm.w.d"` (day d
1406 * (0 <= d <= 6) of week w (1 <= w <= 5) of month m (1 <= m <= 12), day
1407 * 0 is a Sunday). Times are in local wall clock time, the default is
1408 * 02:00:00.
1410 * In Windows, the "tzn[+|–]hh[:mm[:ss]][dzn]" format is used, but also
1411 * accepts POSIX format. The Windows format uses US rules for all time
1412 * zones; daylight savings time is 60 minutes behind the standard time
1413 * with date and time of change taken from Pacific Standard Time.
1414 * Offsets are time values to be added to the local time to get
1415 * Coordinated Universal Time (UTC).
1417 * g_time_zone_new_local() calls this function with the value of the
1418 * `TZ` environment variable. This function itself is independent of
1419 * the value of `TZ`, but if @identifier is %NULL then `/etc/localtime`
1420 * will be consulted to discover the correct time zone on UNIX and the
1421 * registry will be consulted or GetTimeZoneInformation() will be used
1422 * to get the local time zone on Windows.
1424 * If intervals are not available, only time zone rules from `TZ`
1425 * environment variable or other means, then they will be computed
1426 * from year 1900 to 2037. If the maximum year for the rules is
1427 * available and it is greater than 2037, then it will followed
1428 * instead.
1430 * See
1431 * [RFC3339 §5.6](http://tools.ietf.org/html/rfc3339#section-5.6)
1432 * for a precise definition of valid RFC3339 time offsets
1433 * (the `time-offset` expansion) and ISO 8601 for the
1434 * full list of valid time offsets. See
1435 * [The GNU C Library manual](http://www.gnu.org/s/libc/manual/html_node/TZ-Variable.html)
1436 * for an explanation of the possible
1437 * values of the `TZ` environment variable. See
1438 * [Microsoft Time Zone Index Values](http://msdn.microsoft.com/en-us/library/ms912391%28v=winembedded.11%29.aspx)
1439 * for the list of time zones on Windows.
1441 * You should release the return value by calling g_time_zone_unref()
1442 * when you are done with it.
1444 * Returns: the requested timezone
1446 * Since: 2.26
1448 GTimeZone *
1449 g_time_zone_new (const gchar *identifier)
1451 GTimeZone *tz = NULL;
1452 TimeZoneRule *rules;
1453 gint rules_num;
1454 gchar *resolved_identifier = NULL;
1456 G_LOCK (time_zones);
1457 if (time_zones == NULL)
1458 time_zones = g_hash_table_new (g_str_hash, g_str_equal);
1460 if (identifier)
1462 tz = g_hash_table_lookup (time_zones, identifier);
1463 if (tz)
1465 g_atomic_int_inc (&tz->ref_count);
1466 G_UNLOCK (time_zones);
1467 return tz;
1471 tz = g_slice_new0 (GTimeZone);
1472 tz->ref_count = 0;
1474 zone_for_constant_offset (tz, identifier);
1476 if (tz->t_info == NULL &&
1477 (rules_num = rules_from_identifier (identifier, &resolved_identifier, &rules)))
1479 init_zone_from_rules (tz, rules, rules_num, g_steal_pointer (&resolved_identifier));
1480 g_free (rules);
1483 if (tz->t_info == NULL)
1485 #ifdef G_OS_UNIX
1486 GBytes *zoneinfo = zone_info_unix (identifier, &resolved_identifier);
1487 if (zoneinfo != NULL)
1489 init_zone_from_iana_info (tz, zoneinfo, g_steal_pointer (&resolved_identifier));
1490 g_bytes_unref (zoneinfo);
1492 #elif defined (G_OS_WIN32)
1493 if ((rules_num = rules_from_windows_time_zone (identifier,
1494 &resolved_identifier,
1495 &rules)))
1497 init_zone_from_rules (tz, rules, rules_num, g_steal_pointer (&resolved_identifier));
1498 g_free (rules);
1500 #endif
1503 #if defined (G_OS_WIN32)
1504 if (tz->t_info == NULL)
1506 if (identifier == NULL)
1508 TIME_ZONE_INFORMATION tzi;
1510 if (GetTimeZoneInformation (&tzi) != TIME_ZONE_ID_INVALID)
1512 rules = g_new0 (TimeZoneRule, 2);
1514 rule_from_windows_time_zone_info (&rules[0], &tzi);
1516 memset (rules[0].std_name, 0, NAME_SIZE);
1517 memset (rules[0].dlt_name, 0, NAME_SIZE);
1519 rules[0].start_year = MIN_TZYEAR;
1520 rules[1].start_year = MAX_TZYEAR;
1522 init_zone_from_rules (tz, rules, 2, windows_default_tzname ());
1524 g_free (rules);
1528 #endif
1530 g_free (resolved_identifier);
1532 /* Always fall back to UTC. */
1533 if (tz->t_info == NULL)
1534 zone_for_constant_offset (tz, "UTC");
1536 g_assert (tz->name != NULL);
1537 g_assert (tz->t_info != NULL);
1539 if (tz->t_info != NULL)
1541 if (identifier)
1542 g_hash_table_insert (time_zones, tz->name, tz);
1544 g_atomic_int_inc (&tz->ref_count);
1545 G_UNLOCK (time_zones);
1547 return tz;
1551 * g_time_zone_new_utc:
1553 * Creates a #GTimeZone corresponding to UTC.
1555 * This is equivalent to calling g_time_zone_new() with a value like
1556 * "Z", "UTC", "+00", etc.
1558 * You should release the return value by calling g_time_zone_unref()
1559 * when you are done with it.
1561 * Returns: the universal timezone
1563 * Since: 2.26
1565 GTimeZone *
1566 g_time_zone_new_utc (void)
1568 return g_time_zone_new ("UTC");
1572 * g_time_zone_new_local:
1574 * Creates a #GTimeZone corresponding to local time. The local time
1575 * zone may change between invocations to this function; for example,
1576 * if the system administrator changes it.
1578 * This is equivalent to calling g_time_zone_new() with the value of
1579 * the `TZ` environment variable (including the possibility of %NULL).
1581 * You should release the return value by calling g_time_zone_unref()
1582 * when you are done with it.
1584 * Returns: the local timezone
1586 * Since: 2.26
1588 GTimeZone *
1589 g_time_zone_new_local (void)
1591 return g_time_zone_new (getenv ("TZ"));
1595 * g_time_zone_new_offset:
1596 * @seconds: offset to UTC, in seconds
1598 * Creates a #GTimeZone corresponding to the given constant offset from UTC,
1599 * in seconds.
1601 * This is equivalent to calling g_time_zone_new() with a string in the form
1602 * `[+|-]hh[:mm[:ss]]`.
1604 * Returns: (transfer full): a timezone at the given offset from UTC
1605 * Since: 2.58
1607 GTimeZone *
1608 g_time_zone_new_offset (gint32 seconds)
1610 GTimeZone *tz = NULL;
1611 gchar *identifier = NULL;
1613 /* Seemingly, we should be using @seconds directly to set the
1614 * #TransitionInfo.gmt_offset to avoid all this string building and parsing.
1615 * However, we always need to set the #GTimeZone.name to a constructed
1616 * string anyway, so we might as well reuse its code. */
1617 identifier = g_strdup_printf ("%c%02u:%02u:%02u",
1618 (seconds >= 0) ? '+' : '-',
1619 (ABS (seconds) / 60) / 60,
1620 (ABS (seconds) / 60) % 60,
1621 ABS (seconds) % 60);
1622 tz = g_time_zone_new (identifier);
1623 g_free (identifier);
1625 g_assert (g_time_zone_get_offset (tz, 0) == seconds);
1627 return tz;
1630 #define TRANSITION(n) g_array_index (tz->transitions, Transition, n)
1631 #define TRANSITION_INFO(n) g_array_index (tz->t_info, TransitionInfo, n)
1633 /* Internal helpers {{{1 */
1634 /* NB: Interval 0 is before the first transition, so there's no
1635 * transition structure to point to which TransitionInfo to
1636 * use. Rule-based zones are set up so that TI 0 is always standard
1637 * time (which is what's in effect before Daylight time got started
1638 * in the early 20th century), but IANA tzfiles don't follow that
1639 * convention. The tzfile documentation says to use the first
1640 * standard-time (i.e., non-DST) tinfo, so that's what we do.
1642 inline static const TransitionInfo*
1643 interval_info (GTimeZone *tz,
1644 guint interval)
1646 guint index;
1647 g_return_val_if_fail (tz->t_info != NULL, NULL);
1648 if (interval && tz->transitions && interval <= tz->transitions->len)
1649 index = (TRANSITION(interval - 1)).info_index;
1650 else
1652 for (index = 0; index < tz->t_info->len; index++)
1654 TransitionInfo *tzinfo = &(TRANSITION_INFO(index));
1655 if (!tzinfo->is_dst)
1656 return tzinfo;
1658 index = 0;
1661 return &(TRANSITION_INFO(index));
1664 inline static gint64
1665 interval_start (GTimeZone *tz,
1666 guint interval)
1668 if (!interval || tz->transitions == NULL || tz->transitions->len == 0)
1669 return G_MININT64;
1670 if (interval > tz->transitions->len)
1671 interval = tz->transitions->len;
1672 return (TRANSITION(interval - 1)).time;
1675 inline static gint64
1676 interval_end (GTimeZone *tz,
1677 guint interval)
1679 if (tz->transitions && interval < tz->transitions->len)
1681 gint64 lim = (TRANSITION(interval)).time;
1682 return lim - (lim != G_MININT64);
1684 return G_MAXINT64;
1687 inline static gint32
1688 interval_offset (GTimeZone *tz,
1689 guint interval)
1691 g_return_val_if_fail (tz->t_info != NULL, 0);
1692 return interval_info (tz, interval)->gmt_offset;
1695 inline static gboolean
1696 interval_isdst (GTimeZone *tz,
1697 guint interval)
1699 g_return_val_if_fail (tz->t_info != NULL, 0);
1700 return interval_info (tz, interval)->is_dst;
1704 inline static gchar*
1705 interval_abbrev (GTimeZone *tz,
1706 guint interval)
1708 g_return_val_if_fail (tz->t_info != NULL, 0);
1709 return interval_info (tz, interval)->abbrev;
1712 inline static gint64
1713 interval_local_start (GTimeZone *tz,
1714 guint interval)
1716 if (interval)
1717 return interval_start (tz, interval) + interval_offset (tz, interval);
1719 return G_MININT64;
1722 inline static gint64
1723 interval_local_end (GTimeZone *tz,
1724 guint interval)
1726 if (tz->transitions && interval < tz->transitions->len)
1727 return interval_end (tz, interval) + interval_offset (tz, interval);
1729 return G_MAXINT64;
1732 static gboolean
1733 interval_valid (GTimeZone *tz,
1734 guint interval)
1736 if ( tz->transitions == NULL)
1737 return interval == 0;
1738 return interval <= tz->transitions->len;
1741 /* g_time_zone_find_interval() {{{1 */
1744 * g_time_zone_adjust_time:
1745 * @tz: a #GTimeZone
1746 * @type: the #GTimeType of @time_
1747 * @time_: a pointer to a number of seconds since January 1, 1970
1749 * Finds an interval within @tz that corresponds to the given @time_,
1750 * possibly adjusting @time_ if required to fit into an interval.
1751 * The meaning of @time_ depends on @type.
1753 * This function is similar to g_time_zone_find_interval(), with the
1754 * difference that it always succeeds (by making the adjustments
1755 * described below).
1757 * In any of the cases where g_time_zone_find_interval() succeeds then
1758 * this function returns the same value, without modifying @time_.
1760 * This function may, however, modify @time_ in order to deal with
1761 * non-existent times. If the non-existent local @time_ of 02:30 were
1762 * requested on March 14th 2010 in Toronto then this function would
1763 * adjust @time_ to be 03:00 and return the interval containing the
1764 * adjusted time.
1766 * Returns: the interval containing @time_, never -1
1768 * Since: 2.26
1770 gint
1771 g_time_zone_adjust_time (GTimeZone *tz,
1772 GTimeType type,
1773 gint64 *time_)
1775 gint i;
1776 guint intervals;
1778 if (tz->transitions == NULL)
1779 return 0;
1781 intervals = tz->transitions->len;
1783 /* find the interval containing *time UTC
1784 * TODO: this could be binary searched (or better) */
1785 for (i = 0; i <= intervals; i++)
1786 if (*time_ <= interval_end (tz, i))
1787 break;
1789 g_assert (interval_start (tz, i) <= *time_ && *time_ <= interval_end (tz, i));
1791 if (type != G_TIME_TYPE_UNIVERSAL)
1793 if (*time_ < interval_local_start (tz, i))
1794 /* if time came before the start of this interval... */
1796 i--;
1798 /* if it's not in the previous interval... */
1799 if (*time_ > interval_local_end (tz, i))
1801 /* it doesn't exist. fast-forward it. */
1802 i++;
1803 *time_ = interval_local_start (tz, i);
1807 else if (*time_ > interval_local_end (tz, i))
1808 /* if time came after the end of this interval... */
1810 i++;
1812 /* if it's not in the next interval... */
1813 if (*time_ < interval_local_start (tz, i))
1814 /* it doesn't exist. fast-forward it. */
1815 *time_ = interval_local_start (tz, i);
1818 else if (interval_isdst (tz, i) != type)
1819 /* it's in this interval, but dst flag doesn't match.
1820 * check neighbours for a better fit. */
1822 if (i && *time_ <= interval_local_end (tz, i - 1))
1823 i--;
1825 else if (i < intervals &&
1826 *time_ >= interval_local_start (tz, i + 1))
1827 i++;
1831 return i;
1835 * g_time_zone_find_interval:
1836 * @tz: a #GTimeZone
1837 * @type: the #GTimeType of @time_
1838 * @time_: a number of seconds since January 1, 1970
1840 * Finds an the interval within @tz that corresponds to the given @time_.
1841 * The meaning of @time_ depends on @type.
1843 * If @type is %G_TIME_TYPE_UNIVERSAL then this function will always
1844 * succeed (since universal time is monotonic and continuous).
1846 * Otherwise @time_ is treated as local time. The distinction between
1847 * %G_TIME_TYPE_STANDARD and %G_TIME_TYPE_DAYLIGHT is ignored except in
1848 * the case that the given @time_ is ambiguous. In Toronto, for example,
1849 * 01:30 on November 7th 2010 occurred twice (once inside of daylight
1850 * savings time and the next, an hour later, outside of daylight savings
1851 * time). In this case, the different value of @type would result in a
1852 * different interval being returned.
1854 * It is still possible for this function to fail. In Toronto, for
1855 * example, 02:00 on March 14th 2010 does not exist (due to the leap
1856 * forward to begin daylight savings time). -1 is returned in that
1857 * case.
1859 * Returns: the interval containing @time_, or -1 in case of failure
1861 * Since: 2.26
1863 gint
1864 g_time_zone_find_interval (GTimeZone *tz,
1865 GTimeType type,
1866 gint64 time_)
1868 gint i;
1869 guint intervals;
1871 if (tz->transitions == NULL)
1872 return 0;
1873 intervals = tz->transitions->len;
1874 for (i = 0; i <= intervals; i++)
1875 if (time_ <= interval_end (tz, i))
1876 break;
1878 if (type == G_TIME_TYPE_UNIVERSAL)
1879 return i;
1881 if (time_ < interval_local_start (tz, i))
1883 if (time_ > interval_local_end (tz, --i))
1884 return -1;
1887 else if (time_ > interval_local_end (tz, i))
1889 if (time_ < interval_local_start (tz, ++i))
1890 return -1;
1893 else if (interval_isdst (tz, i) != type)
1895 if (i && time_ <= interval_local_end (tz, i - 1))
1896 i--;
1898 else if (i < intervals && time_ >= interval_local_start (tz, i + 1))
1899 i++;
1902 return i;
1905 /* Public API accessors {{{1 */
1908 * g_time_zone_get_abbreviation:
1909 * @tz: a #GTimeZone
1910 * @interval: an interval within the timezone
1912 * Determines the time zone abbreviation to be used during a particular
1913 * @interval of time in the time zone @tz.
1915 * For example, in Toronto this is currently "EST" during the winter
1916 * months and "EDT" during the summer months when daylight savings time
1917 * is in effect.
1919 * Returns: the time zone abbreviation, which belongs to @tz
1921 * Since: 2.26
1923 const gchar *
1924 g_time_zone_get_abbreviation (GTimeZone *tz,
1925 gint interval)
1927 g_return_val_if_fail (interval_valid (tz, (guint)interval), NULL);
1929 return interval_abbrev (tz, (guint)interval);
1933 * g_time_zone_get_offset:
1934 * @tz: a #GTimeZone
1935 * @interval: an interval within the timezone
1937 * Determines the offset to UTC in effect during a particular @interval
1938 * of time in the time zone @tz.
1940 * The offset is the number of seconds that you add to UTC time to
1941 * arrive at local time for @tz (ie: negative numbers for time zones
1942 * west of GMT, positive numbers for east).
1944 * Returns: the number of seconds that should be added to UTC to get the
1945 * local time in @tz
1947 * Since: 2.26
1949 gint32
1950 g_time_zone_get_offset (GTimeZone *tz,
1951 gint interval)
1953 g_return_val_if_fail (interval_valid (tz, (guint)interval), 0);
1955 return interval_offset (tz, (guint)interval);
1959 * g_time_zone_is_dst:
1960 * @tz: a #GTimeZone
1961 * @interval: an interval within the timezone
1963 * Determines if daylight savings time is in effect during a particular
1964 * @interval of time in the time zone @tz.
1966 * Returns: %TRUE if daylight savings time is in effect
1968 * Since: 2.26
1970 gboolean
1971 g_time_zone_is_dst (GTimeZone *tz,
1972 gint interval)
1974 g_return_val_if_fail (interval_valid (tz, interval), FALSE);
1976 if (tz->transitions == NULL)
1977 return FALSE;
1979 return interval_isdst (tz, (guint)interval);
1983 * g_time_zone_get_identifier:
1984 * @tz: a #GTimeZone
1986 * Get the identifier of this #GTimeZone, as passed to g_time_zone_new().
1987 * If the identifier passed at construction time was not recognised, `UTC` will
1988 * be returned. If it was %NULL, the identifier of the local timezone at
1989 * construction time will be returned.
1991 * The identifier will be returned in the same format as provided at
1992 * construction time: if provided as a time offset, that will be returned by
1993 * this function.
1995 * Returns: identifier for this timezone
1996 * Since: 2.58
1998 const gchar *
1999 g_time_zone_get_identifier (GTimeZone *tz)
2001 g_return_val_if_fail (tz != NULL, NULL);
2003 return tz->name;
2006 /* Epilogue {{{1 */
2007 /* vim:set foldmethod=marker: */