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 of the licence, 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, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
19 * Author: Ryan Lortie <desrt@desrt.ca>
26 #include "gtimezone.h"
32 #include "gmappedfile.h"
33 #include "gtestutils.h"
34 #include "gfileutils.h"
35 #include "gstrfuncs.h"
40 #include "gdatetime.h"
51 * @short_description: a structure representing a time zone
52 * @see_also: #GDateTime
54 * #GTimeZone is a structure that represents a time zone, at no
55 * particular point in time. It is refcounted and immutable.
57 * A time zone contains a number of intervals. Each interval has
58 * an abbreviation to describe it, an offet to UTC and a flag indicating
59 * if the daylight savings time is in effect during that interval. A
60 * time zone always has at least one interval -- interval 0.
62 * Every UTC time is contained within exactly one interval, but a given
63 * local time may be contained within zero, one or two intervals (due to
64 * incontinuities associated with daylight savings time).
66 * An interval may refer to a specific period of time (eg: the duration
67 * of daylight savings time during 2010) or it may refer to many periods
68 * of time that share the same properties (eg: all periods of daylight
69 * savings time). It is also possible (usually for political reasons)
70 * that some properties (like the abbreviation) change between intervals
71 * without other properties changing.
73 * #GTimeZone is available since GLib 2.26.
79 * #GTimeZone is an opaque structure whose members cannot be accessed
85 /* IANA zoneinfo file format {{{1 */
88 typedef struct { gchar bytes[8]; } gint64_be;
89 typedef struct { gchar bytes[4]; } gint32_be;
90 typedef struct { gchar bytes[4]; } guint32_be;
92 static inline gint64 gint64_from_be (const gint64_be be) {
93 gint64 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT64_FROM_BE (tmp);
96 static inline gint32 gint32_from_be (const gint32_be be) {
97 gint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT32_FROM_BE (tmp);
100 static inline guint32 guint32_from_be (const guint32_be be) {
101 guint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GUINT32_FROM_BE (tmp);
104 /* The layout of an IANA timezone file header */
109 guchar tzh_reserved[15];
111 guint32_be tzh_ttisgmtcnt;
112 guint32_be tzh_ttisstdcnt;
113 guint32_be tzh_leapcnt;
114 guint32_be tzh_timecnt;
115 guint32_be tzh_typecnt;
116 guint32_be tzh_charcnt;
126 /* A Transition Date structure for TZ Rules, an intermediate structure
127 for parsing MSWindows and Environment-variable time zones. It
128 Generalizes MSWindows's SYSTEMTIME struct.
142 /* POSIX Timezone abbreviations are typically 3 or 4 characters, but
143 Microsoft uses 32-character names. We'll use one larger to ensure
144 we have room for the terminating \0.
148 /* A MSWindows-style time zone transition rule. Generalizes the
149 MSWindows TIME_ZONE_INFORMATION struct. Also used to compose time
150 zones from tzset-style identifiers.
157 TimeZoneDate dlt_start;
158 TimeZoneDate dlt_end;
159 gchar std_name[NAME_SIZE];
160 gchar dlt_name[NAME_SIZE];
163 /* GTimeZone's internal representation of a Daylight Savings (Summer)
170 gboolean is_standard;
175 /* GTimeZone's representation of a transition time to or from Daylight
176 Savings (Summer) time and Standard time for the zone. */
183 /* GTimeZone structure */
187 GArray *t_info; /* Array of TransitionInfo */
188 GArray *transitions; /* Array of Transition */
192 G_LOCK_DEFINE_STATIC (time_zones);
193 static GHashTable/*<string?, GTimeZone>*/ *time_zones;
195 #define MIN_TZYEAR 1916 /* Daylight Savings started in WWI */
196 #define MAX_TZYEAR 2999 /* And it's not likely ever to go away, but
197 there's no point in getting carried
204 * Decreases the reference count on @tz.
209 g_time_zone_unref (GTimeZone *tz)
214 ref_count = g_atomic_int_get (&tz->ref_count);
216 g_assert (ref_count > 0);
220 if (tz->name != NULL)
224 /* someone else might have grabbed a ref in the meantime */
225 if G_UNLIKELY (g_atomic_int_get (&tz->ref_count) != 1)
227 G_UNLOCK(time_zones);
231 g_hash_table_remove (time_zones, tz->name);
232 G_UNLOCK(time_zones);
235 if (tz->t_info != NULL)
238 for (idx = 0; idx < tz->t_info->len; idx++)
240 TransitionInfo *info = &g_array_index (tz->t_info, TransitionInfo, idx);
241 g_free (info->abbrev);
243 g_array_free (tz->t_info, TRUE);
245 if (tz->transitions != NULL)
246 g_array_free (tz->transitions, TRUE);
249 g_slice_free (GTimeZone, tz);
252 else if G_UNLIKELY (!g_atomic_int_compare_and_exchange (&tz->ref_count,
262 * Increases the reference count on @tz.
264 * Returns: a new reference to @tz.
269 g_time_zone_ref (GTimeZone *tz)
271 g_assert (tz->ref_count > 0);
273 g_atomic_int_inc (&tz->ref_count);
278 /* fake zoneinfo creation (for RFC3339/ISO 8601 timezones) {{{1 */
280 * parses strings of the form h or hh[[:]mm[[[:]ss]]] where:
286 parse_time (const gchar *time_,
289 if (*time_ < '0' || '9' < *time_)
292 *offset = 60 * 60 * (*time_++ - '0');
299 if (*time_ < '0' || '9' < *time_)
303 *offset += 60 * 60 * (*time_++ - '0');
305 if (*offset > 23 * 60 * 60)
315 if (*time_ < '0' || '5' < *time_)
318 *offset += 10 * 60 * (*time_++ - '0');
320 if (*time_ < '0' || '9' < *time_)
323 *offset += 60 * (*time_++ - '0');
331 if (*time_ < '0' || '5' < *time_)
334 *offset += 10 * (*time_++ - '0');
336 if (*time_ < '0' || '9' < *time_)
339 *offset += *time_++ - '0';
341 return *time_ == '\0';
345 parse_constant_offset (const gchar *name,
348 if (g_strcmp0 (name, "UTC") == 0)
354 if (*name >= '0' && '9' >= *name)
355 return parse_time (name, offset);
364 return parse_time (name, offset);
367 if (parse_time (name, offset))
379 zone_for_constant_offset (GTimeZone *gtz, const gchar *name)
384 if (name == NULL || !parse_constant_offset (name, &offset))
387 info.gmt_offset = offset;
389 info.is_standard = TRUE;
391 info.abbrev = g_strdup (name);
394 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), 1);
395 g_array_append_val (gtz->t_info, info);
397 /* Constant offset, no transitions */
398 gtz->transitions = NULL;
403 zone_info_unix (const gchar *identifier)
406 GMappedFile *file = NULL;
407 GBytes *zoneinfo = NULL;
409 /* identifier can be a relative or absolute path name;
410 if relative, it is interpreted starting from /usr/share/zoneinfo
411 while the POSIX standard says it should start with :,
412 glibc allows both syntaxes, so we should too */
413 if (identifier != NULL)
417 tzdir = getenv ("TZDIR");
419 tzdir = "/usr/share/zoneinfo";
421 if (*identifier == ':')
424 if (g_path_is_absolute (identifier))
425 filename = g_strdup (identifier);
427 filename = g_build_filename (tzdir, identifier, NULL);
430 filename = g_strdup ("/etc/localtime");
432 file = g_mapped_file_new (filename, FALSE, NULL);
435 zoneinfo = g_bytes_new_with_free_func (g_mapped_file_get_contents (file),
436 g_mapped_file_get_length (file),
437 (GDestroyNotify)g_mapped_file_unref,
438 g_mapped_file_ref (file));
439 g_mapped_file_unref (file);
446 init_zone_from_iana_info (GTimeZone *gtz, GBytes *zoneinfo)
450 guint32 time_count, type_count, leap_count, isgmt_count;
451 guint32 isstd_count, char_count ;
452 guint8 *tz_transitions, *tz_type_index, *tz_ttinfo;
453 guint8 *tz_leaps, *tz_isgmt, *tz_isstd;
455 gsize timesize = sizeof (gint32), countsize = sizeof (gint32);
456 const struct tzhead *header = g_bytes_get_data (zoneinfo, &size);
458 g_return_if_fail (size >= sizeof (struct tzhead) &&
459 memcmp (header, "TZif", 4) == 0);
461 if (header->tzh_version == '2')
463 /* Skip ahead to the newer 64-bit data if it's available. */
464 header = (const struct tzhead *)
465 (((const gchar *) (header + 1)) +
466 guint32_from_be(header->tzh_ttisgmtcnt) +
467 guint32_from_be(header->tzh_ttisstdcnt) +
468 8 * guint32_from_be(header->tzh_leapcnt) +
469 5 * guint32_from_be(header->tzh_timecnt) +
470 6 * guint32_from_be(header->tzh_typecnt) +
471 guint32_from_be(header->tzh_charcnt));
472 timesize = sizeof (gint64);
474 time_count = guint32_from_be(header->tzh_timecnt);
475 type_count = guint32_from_be(header->tzh_typecnt);
476 leap_count = guint32_from_be(header->tzh_leapcnt);
477 isgmt_count = guint32_from_be(header->tzh_ttisgmtcnt);
478 isstd_count = guint32_from_be(header->tzh_ttisstdcnt);
479 char_count = guint32_from_be(header->tzh_charcnt);
481 g_assert (type_count == isgmt_count);
482 g_assert (type_count == isstd_count);
484 tz_transitions = ((guint8 *) (header) + sizeof (*header));
485 tz_type_index = tz_transitions + timesize * time_count;
486 tz_ttinfo = tz_type_index + time_count;
487 tz_abbrs = tz_ttinfo + sizeof (struct ttinfo) * type_count;
488 tz_leaps = tz_abbrs + char_count;
489 tz_isstd = tz_leaps + (timesize + countsize) * leap_count;
490 tz_isgmt = tz_isstd + isstd_count;
492 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo),
494 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition),
497 for (index = 0; index < type_count; index++)
499 TransitionInfo t_info;
500 struct ttinfo info = ((struct ttinfo*)tz_ttinfo)[index];
501 t_info.gmt_offset = gint32_from_be (info.tt_gmtoff);
502 t_info.is_dst = info.tt_isdst ? TRUE : FALSE;
503 t_info.is_standard = tz_isstd[index] ? TRUE : FALSE;
504 t_info.is_gmt = tz_isgmt[index] ? TRUE : FALSE;
505 t_info.abbrev = g_strdup ((gchar *) &tz_abbrs[info.tt_abbrind]);
506 g_array_append_val (gtz->t_info, t_info);
509 for (index = 0; index < time_count; index++)
512 if (header->tzh_version == '2')
513 trans.time = gint64_from_be (((gint64_be*)tz_transitions)[index]);
515 trans.time = gint32_from_be (((gint32_be*)tz_transitions)[index]);
516 trans.info_index = tz_type_index[index];
517 g_assert (trans.info_index >= 0);
518 g_assert (trans.info_index < gtz->t_info->len);
519 g_array_append_val (gtz->transitions, trans);
523 #elif defined (G_OS_WIN32)
526 copy_windows_systemtime (SYSTEMTIME *s_time, TimeZoneDate *tzdate)
528 tzdate->sec = s_time->wSecond;
529 tzdate->min = s_time->wMinute;
530 tzdate->hour = s_time->wHour;
531 tzdate->mon = s_time->wMonth;
532 tzdate->year = s_time->wYear;
533 tzdate->wday = s_time->wDayOfWeek ? s_time->wDayOfWeek : 7;
537 tzdate->mday = s_time->wDay;
541 tzdate->week = s_time->wDay;
544 /* UTC = local time + bias while local time = UTC + offset */
546 rule_from_windows_time_zone_info (TimeZoneRule *rule,
547 TIME_ZONE_INFORMATION *tzi)
550 if (tzi->StandardDate.wMonth)
552 rule->std_offset = -(tzi->Bias + tzi->StandardBias) * 60;
553 rule->dlt_offset = -(tzi->Bias + tzi->DaylightBias) * 60;
554 copy_windows_systemtime (&(tzi->DaylightDate), &(rule->dlt_start));
556 copy_windows_systemtime (&(tzi->StandardDate), &(rule->dlt_end));
562 rule->std_offset = -tzi->Bias * 60;
563 rule->dlt_start.mon = 0;
565 strncpy (rule->std_name, (gchar*)tzi->StandardName, NAME_SIZE - 1);
566 strncpy (rule->dlt_name, (gchar*)tzi->DaylightName, NAME_SIZE - 1);
570 windows_default_tzname (void)
572 const gchar *subkey =
573 "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation";
575 gchar *key_name = NULL;
576 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
577 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
580 if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
581 NULL, &size) == ERROR_SUCCESS)
583 key_name = g_malloc ((gint)size);
584 if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
585 (LPBYTE)key_name, &size) != ERROR_SUCCESS)
601 SYSTEMTIME StandardDate;
602 SYSTEMTIME DaylightDate;
606 system_time_copy (SYSTEMTIME *orig, SYSTEMTIME *target)
608 g_return_if_fail (orig != NULL);
609 g_return_if_fail (target != NULL);
611 target->wYear = orig->wYear;
612 target->wMonth = orig->wMonth;
613 target->wDayOfWeek = orig->wDayOfWeek;
614 target->wDay = orig->wDay;
615 target->wHour = orig->wHour;
616 target->wMinute = orig->wMinute;
617 target->wSecond = orig->wSecond;
618 target->wMilliseconds = orig->wMilliseconds;
622 register_tzi_to_tzi (RegTZI *reg, TIME_ZONE_INFORMATION *tzi)
624 g_return_if_fail (reg != NULL);
625 g_return_if_fail (tzi != NULL);
626 tzi->Bias = reg->Bias;
627 system_time_copy (&(reg->StandardDate), &(tzi->StandardDate));
628 tzi->StandardBias = reg->StandardBias;
629 system_time_copy (&(reg->DaylightDate), &(tzi->DaylightDate));
630 tzi->DaylightBias = reg->DaylightBias;
634 rules_from_windows_time_zone (const gchar *identifier, TimeZoneRule **rules)
637 gchar *subkey, *subkey_dynamic;
638 gchar *key_name = NULL;
639 const gchar *reg_key =
640 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\";
641 TIME_ZONE_INFORMATION tzi;
644 RegTZI regtzi, regtzi_prev;
650 key_name = windows_default_tzname ();
652 key_name = g_strdup (identifier);
657 subkey = g_strconcat (reg_key, key_name, NULL);
658 subkey_dynamic = g_strconcat (subkey, "\\Dynamic DST", NULL);
660 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
661 KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
663 size = sizeof tzi.StandardName;
664 if (RegQueryValueExA (key, "Std", NULL, NULL,
665 (LPBYTE)&(tzi.StandardName), &size) != ERROR_SUCCESS)
668 size = sizeof tzi.DaylightName;
670 if (RegQueryValueExA (key, "Dlt", NULL, NULL,
671 (LPBYTE)&(tzi.DaylightName), &size) != ERROR_SUCCESS)
675 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey_dynamic, 0,
676 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
683 if (RegQueryValueExA (key, "FirstEntry", NULL, NULL,
684 (LPBYTE) &first, &size) != ERROR_SUCCESS)
688 if (RegQueryValueExA (key, "LastEntry", NULL, NULL,
689 (LPBYTE) &last, &size) != ERROR_SUCCESS)
692 rules_num = last - first + 2;
693 *rules = g_new0 (TimeZoneRule, rules_num);
695 for (year = first, i = 0; year <= last; year++)
697 s = g_strdup_printf ("%d", year);
699 size = sizeof regtzi;
700 if (RegQueryValueExA (key, s, NULL, NULL,
701 (LPBYTE) ®tzi, &size) != ERROR_SUCCESS)
710 if (year > first && memcmp (®tzi_prev, ®tzi, sizeof regtzi) == 0)
713 memcpy (®tzi_prev, ®tzi, sizeof regtzi);
715 register_tzi_to_tzi (®tzi, &tzi);
716 rule_from_windows_time_zone_info (&(*rules)[i], &tzi);
717 (*rules)[i++].start_year = year;
725 else if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
726 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
728 size = sizeof regtzi;
729 if (RegQueryValueExA (key, "TZI", NULL, NULL,
730 (LPBYTE) ®tzi, &size) == ERROR_SUCCESS)
733 *rules = g_new0 (TimeZoneRule, 2);
734 register_tzi_to_tzi (®tzi, &tzi);
735 rule_from_windows_time_zone_info (&(*rules)[0], &tzi);
741 g_free (subkey_dynamic);
747 (*rules)[0].start_year = MIN_TZYEAR;
748 if ((*rules)[rules_num - 2].start_year < MAX_TZYEAR)
749 (*rules)[rules_num - 1].start_year = MAX_TZYEAR;
751 (*rules)[rules_num - 1].start_year = (*rules)[rules_num - 2].start_year + 1;
762 find_relative_date (TimeZoneDate *buffer)
766 g_date_clear (&date, 1);
769 /* Get last day if last is needed, first day otherwise */
770 if (buffer->mon == 13 || buffer->mon == 14) /* Julian Date */
772 g_date_set_dmy (&date, 1, 1, buffer->year);
773 if (wday >= 59 && buffer->mon == 13 && g_date_is_leap_year (buffer->year))
774 g_date_add_days (&date, wday);
776 g_date_add_days (&date, wday - 1);
777 buffer->mon = (int) g_date_get_month (&date);
778 buffer->mday = (int) g_date_get_day (&date);
784 guint days_in_month = g_date_days_in_month (buffer->mon, buffer->year);
785 GDateWeekday first_wday;
787 g_date_set_dmy (&date, 1, buffer->mon, buffer->year);
788 first_wday = g_date_get_weekday (&date);
790 if (first_wday > wday)
792 /* week is 1 <= w <= 5, we need 0-based */
793 days = 7 * (buffer->week - 1) + wday - first_wday;
795 while (days > days_in_month)
798 g_date_add_days (&date, days);
800 buffer->mday = g_date_get_day (&date);
804 /* Offset is previous offset of local time. Returns 0 if month is 0 */
806 boundary_for_year (TimeZoneDate *boundary,
812 const guint64 unix_epoch_start = 719163L;
813 const guint64 seconds_per_day = 86400L;
819 if (boundary->year == 0)
824 find_relative_date (&buffer);
827 g_assert (buffer.year == year);
828 g_date_clear (&date, 1);
829 g_date_set_dmy (&date, buffer.mday, buffer.mon, buffer.year);
830 return ((g_date_get_julian (&date) - unix_epoch_start) * seconds_per_day +
831 buffer.hour * 3600 + buffer.min * 60 + buffer.sec - offset);
835 fill_transition_info_from_rule (TransitionInfo *info,
839 gint offset = is_dst ? rule->dlt_offset : rule->std_offset;
840 gchar *name = is_dst ? rule->dlt_name : rule->std_name;
842 info->gmt_offset = offset;
843 info->is_dst = is_dst;
844 info->is_standard = FALSE;
845 info->is_gmt = FALSE;
848 info->abbrev = g_strdup (name);
851 info->abbrev = g_strdup_printf ("%+03d%02d",
853 (int) abs (offset / 60) % 60);
857 init_zone_from_rules (GTimeZone *gtz,
861 guint type_count = 0, trans_count = 0, info_index = 0;
862 guint ri; /* rule index */
863 gboolean skip_first_std_trans = TRUE;
869 /* Last rule only contains max year */
870 for (ri = 0; ri < rules_num - 1; ri++)
872 if (rules[ri].dlt_start.mon || rules[ri].dlt_end.mon)
874 guint rulespan = (rules[ri + 1].start_year - rules[ri].start_year);
875 guint transitions = rules[ri].dlt_start.mon > 0 ? 1 : 0;
876 transitions += rules[ri].dlt_end.mon > 0 ? 1 : 0;
877 type_count += rules[ri].dlt_start.mon > 0 ? 2 : 1;
878 trans_count += transitions * rulespan;
884 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), type_count);
885 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition), trans_count);
887 last_offset = rules[0].std_offset;
889 for (ri = 0; ri < rules_num - 1; ri++)
891 if ((rules[ri].std_offset || rules[ri].dlt_offset) &&
892 rules[ri].dlt_start.mon == 0 && rules[ri].dlt_end.mon == 0)
894 TransitionInfo std_info;
896 fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
897 g_array_append_val (gtz->t_info, std_info);
900 ((rules[ri - 1].dlt_start.mon > 12 &&
901 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
902 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
904 /* The previous rule was a southern hemisphere rule that
905 starts the year with DST, so we need to add a
906 transition to return to standard time */
907 guint year = rules[ri].start_year;
908 gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
910 Transition std_trans = {std_time, info_index};
911 g_array_append_val (gtz->transitions, std_trans);
914 last_offset = rules[ri].std_offset;
916 skip_first_std_trans = TRUE;
918 else if (rules[ri].std_offset || rules[ri].dlt_offset)
920 const guint start_year = rules[ri].start_year;
921 const guint end_year = rules[ri + 1].start_year;
924 TransitionInfo std_info, dlt_info;
925 if (rules[ri].dlt_start.mon > 12)
926 dlt_first = rules[ri].dlt_start.wday > rules[ri].dlt_end.wday;
928 dlt_first = rules[ri].dlt_start.mon > rules[ri].dlt_end.mon;
929 /* Standard rules are always even, because before the first
930 transition is always standard time, and 0 is even. */
931 fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
932 fill_transition_info_from_rule (&dlt_info, &(rules[ri]), TRUE);
934 g_array_append_val (gtz->t_info, std_info);
935 g_array_append_val (gtz->t_info, dlt_info);
937 /* Transition dates. We hope that a year which ends daylight
938 time in a southern-hemisphere country (i.e., one that
939 begins the year in daylight time) will include a rule
940 which has only a dlt_end. */
941 for (year = start_year; year < end_year; year++)
943 gint32 dlt_offset = (dlt_first ? last_offset :
944 rules[ri].dlt_offset);
945 gint32 std_offset = (dlt_first ? rules[ri].std_offset :
947 /* NB: boundary_for_year returns 0 if mon == 0 */
948 gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
950 gint64 dlt_time = boundary_for_year (&rules[ri].dlt_start,
952 Transition std_trans = {std_time, info_index};
953 Transition dlt_trans = {dlt_time, info_index + 1};
954 last_offset = (dlt_first ? rules[ri].dlt_offset :
955 rules[ri].std_offset);
958 if (skip_first_std_trans)
959 skip_first_std_trans = FALSE;
961 g_array_append_val (gtz->transitions, std_trans);
963 g_array_append_val (gtz->transitions, dlt_trans);
968 g_array_append_val (gtz->transitions, dlt_trans);
970 g_array_append_val (gtz->transitions, std_trans);
978 ((rules[ri - 1].dlt_start.mon > 12 &&
979 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
980 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
982 /* The previous rule was a southern hemisphere rule that
983 starts the year with DST, so we need to add a
984 transition to return to standard time */
986 guint year = rules[ri].start_year;
988 fill_transition_info_from_rule (&info, &(rules[ri - 1]), FALSE);
989 g_array_append_val (gtz->t_info, info);
990 trans.time = boundary_for_year (&rules[ri - 1].dlt_end,
992 trans.info_index = info_index;
993 g_array_append_val (gtz->transitions, trans);
998 * parses date[/time] for parsing TZ environment variable
1000 * date is either Mm.w.d, Jn or N
1007 * time is either h or hh[[:]mm[[[:]ss]]]
1013 parse_mwd_boundary (gchar **pos, TimeZoneDate *boundary)
1015 gint month, week, day;
1017 if (**pos == '\0' || **pos < '0' || '9' < **pos)
1020 month = *(*pos)++ - '0';
1022 if ((month == 1 && **pos >= '0' && '2' >= **pos) ||
1023 (month == 0 && **pos >= '0' && '9' >= **pos))
1026 month += *(*pos)++ - '0';
1029 if (*(*pos)++ != '.' || month == 0)
1032 if (**pos == '\0' || **pos < '1' || '5' < **pos)
1035 week = *(*pos)++ - '0';
1037 if (*(*pos)++ != '.')
1040 if (**pos == '\0' || **pos < '0' || '6' < **pos)
1043 day = *(*pos)++ - '0';
1049 boundary->mon = month;
1050 boundary->week = week;
1051 boundary->wday = day;
1055 /* Different implementations of tzset interpret the Julian day field
1056 differently. For example, Linux specifies that it should be 1-based
1057 (1 Jan is JD 1) for both Jn and n formats, while zOS and BSD
1058 specify that a Jn JD is 1-based while an n JD is 0-based. Rather
1059 than trying to follow different specs, we will follow GDate's
1060 practice thatIn order to keep it simple, we will follow Linux's
1064 parse_julian_boundary (gchar** pos, TimeZoneDate *boundary,
1065 gboolean ignore_leap)
1070 while (**pos >= '0' && '9' >= **pos)
1073 day += *(*pos)++ - '0';
1076 if (day < 1 || 365 < day)
1079 g_date_clear (&date, 1);
1080 g_date_set_julian (&date, day);
1082 boundary->mon = (int) g_date_get_month (&date);
1083 boundary->mday = (int) g_date_get_day (&date);
1086 if (!ignore_leap && day >= 59)
1093 parse_tz_boundary (const gchar *identifier,
1094 TimeZoneDate *boundary)
1098 pos = (gchar*)identifier;
1099 /* Month-week-weekday */
1103 if (!parse_mwd_boundary (&pos, boundary))
1106 /* Julian date which ignores Feb 29 in leap years */
1107 else if (*pos == 'J')
1110 if (!parse_julian_boundary (&pos, boundary, FALSE))
1113 /* Julian date which counts Feb 29 in leap years */
1114 else if (*pos >= '0' && '9' >= *pos)
1116 if (!parse_julian_boundary (&pos, boundary, TRUE))
1128 if (!parse_time (++pos, &offset))
1131 boundary->hour = offset / 3600;
1132 boundary->min = (offset / 60) % 60;
1133 boundary->sec = offset % 3600;
1144 return *pos == '\0';
1149 create_ruleset_from_rule (TimeZoneRule **rules, TimeZoneRule *rule)
1151 *rules = g_new0 (TimeZoneRule, 2);
1153 (*rules)[0].start_year = MIN_TZYEAR;
1154 (*rules)[1].start_year = MAX_TZYEAR;
1156 (*rules)[0].std_offset = -rule->std_offset;
1157 (*rules)[0].dlt_offset = -rule->dlt_offset;
1158 (*rules)[0].dlt_start = rule->dlt_start;
1159 (*rules)[0].dlt_end = rule->dlt_end;
1160 strcpy ((*rules)[0].std_name, rule->std_name);
1161 strcpy ((*rules)[0].dlt_name, rule->dlt_name);
1166 parse_offset (gchar **pos, gint32 *target)
1169 gchar *target_pos = *pos;
1172 while (**pos == '+' || **pos == '-' || **pos == ':' ||
1173 (**pos >= '0' && '9' >= **pos))
1176 buffer = g_strndup (target_pos, *pos - target_pos);
1177 ret = parse_constant_offset (buffer, target);
1184 parse_identifier_boundary (gchar **pos, TimeZoneDate *target)
1187 gchar *target_pos = *pos;
1190 while (**pos != ',' && **pos != '\0')
1192 buffer = g_strndup (target_pos, *pos - target_pos);
1193 ret = parse_tz_boundary (buffer, target);
1200 set_tz_name (gchar **pos, gchar *buffer, guint size)
1202 gchar *name_pos = *pos;
1205 /* Name is ASCII alpha (Is this necessarily true?) */
1206 while (g_ascii_isalpha (**pos))
1209 /* Name should be three or more alphabetic characters */
1210 if (*pos - name_pos < 3)
1213 memset (buffer, 0, NAME_SIZE);
1214 /* name_pos isn't 0-terminated, so we have to limit the length expressly */
1215 len = *pos - name_pos > size - 1 ? size - 1 : *pos - name_pos;
1216 strncpy (buffer, name_pos, len);
1221 parse_identifier_boundaries (gchar **pos, TimeZoneRule *tzr)
1223 if (*(*pos)++ != ',')
1227 if (!parse_identifier_boundary (pos, &(tzr->dlt_start)) || *(*pos)++ != ',')
1231 if (!parse_identifier_boundary (pos, &(tzr->dlt_end)))
1237 * Creates an array of TimeZoneRule from a TZ environment variable
1238 * type of identifier. Should free rules afterwards
1241 rules_from_identifier (const gchar *identifier,
1242 TimeZoneRule **rules)
1250 pos = (gchar*)identifier;
1251 memset (&tzr, 0, sizeof (tzr));
1252 /* Standard offset */
1253 if (!(set_tz_name (&pos, tzr.std_name, NAME_SIZE)) ||
1254 !parse_offset (&pos, &(tzr.std_offset)))
1258 return create_ruleset_from_rule (rules, &tzr);
1261 if (!(set_tz_name (&pos, tzr.dlt_name, NAME_SIZE)))
1263 parse_offset (&pos, &(tzr.dlt_offset));
1264 if (tzr.dlt_offset == 0) /* No daylight offset given, assume it's 1
1265 hour earlier that standard */
1266 tzr.dlt_offset = tzr.std_offset - 3600;
1269 /* Windows allows us to use the US DST boundaries if they're not given */
1272 guint rules_num = 0;
1274 /* Use US rules, Windows' default is Pacific Standard Time */
1275 if ((rules_num = rules_from_windows_time_zone ("Pacific Standard Time",
1278 for (i = 0; i < rules_num - 1; i++)
1280 (*rules)[i].std_offset = - tzr.std_offset;
1281 (*rules)[i].dlt_offset = - tzr.dlt_offset;
1282 strcpy ((*rules)[i].std_name, tzr.std_name);
1283 strcpy ((*rules)[i].dlt_name, tzr.dlt_name);
1294 /* Start and end required (format 2) */
1295 if (!parse_identifier_boundaries (&pos, &tzr))
1298 return create_ruleset_from_rule (rules, &tzr);
1301 /* Construction {{{1 */
1304 * @identifier: (allow-none): a timezone identifier
1306 * Creates a #GTimeZone corresponding to @identifier.
1308 * @identifier can either be an RFC3339/ISO 8601 time offset or
1309 * something that would pass as a valid value for the
1310 * <varname>TZ</varname> environment variable (including %NULL).
1312 * In Windows, @identifier can also be the unlocalized name of a time
1313 * zone for standard time, for example "Pacific Standard Time".
1315 * Valid RFC3339 time offsets are <literal>"Z"</literal> (for UTC) or
1316 * <literal>"±hh:mm"</literal>. ISO 8601 additionally specifies
1317 * <literal>"±hhmm"</literal> and <literal>"±hh"</literal>. Offsets are
1318 * time values to be added to Coordinated Universal Time (UTC) to get
1321 * In Unix, the <varname>TZ</varname> environment variable typically
1322 * corresponds to the name of a file in the zoneinfo database, or
1323 * string in "std offset [dst [offset],start[/time],end[/time]]"
1324 * (POSIX) format. There are no spaces in the specification. The
1325 * name of standard and daylight savings time zone must be three or more
1326 * alphabetic characters. Offsets are time values to be added to local
1327 * time to get Coordinated Universal Time (UTC) and should be
1328 * <literal>"[±]hh[[:]mm[:ss]]"</literal>. Dates are either
1329 * <literal>"Jn"</literal> (Julian day with n between 1 and 365, leap
1330 * years not counted), <literal>"n"</literal> (zero-based Julian day
1331 * with n between 0 and 365) or <literal>"Mm.w.d"</literal> (day d
1332 * (0 <= d <= 6) of week w (1 <= w <= 5) of month m (1 <= m <= 12), day
1333 * 0 is a Sunday). Times are in local wall clock time, the default is
1336 * In Windows, the "tzn[+|–]hh[:mm[:ss]][dzn]" format is used, but also
1337 * accepts POSIX format. The Windows format uses US rules for all time
1338 * zones; daylight savings time is 60 minutes behind the standard time
1339 * with date and time of change taken from Pacific Standard Time.
1340 * Offsets are time values to be added to the local time to get
1341 * Coordinated Universal Time (UTC).
1343 * g_time_zone_new_local() calls this function with the value of the
1344 * <varname>TZ</varname> environment variable. This function itself is
1345 * independent of the value of <varname>TZ</varname>, but if @identifier
1346 * is %NULL then <filename>/etc/localtime</filename> will be consulted
1347 * to discover the correct time zone on Unix and the registry will be
1348 * consulted or GetTimeZoneInformation() will be used to get the local
1349 * time zone on Windows.
1351 * If intervals are not available, only time zone rules from
1352 * <varname>TZ</varname> environment variable or other means, then they
1353 * will be computed from year 1900 to 2037. If the maximum year for the
1354 * rules is available and it is greater than 2037, then it will followed
1358 * url='http://tools.ietf.org/html/rfc3339#section-5.6'>RFC3339
1359 * §5.6</ulink> for a precise definition of valid RFC3339 time offsets
1360 * (the <varname>time-offset</varname> expansion) and ISO 8601 for the
1361 * full list of valid time offsets. See <ulink
1362 * url='http://www.gnu.org/s/libc/manual/html_node/TZ-Variable.html'>The
1363 * GNU C Library manual</ulink> for an explanation of the possible
1364 * values of the <varname>TZ</varname> environment variable. See <ulink
1365 * url='http://msdn.microsoft.com/en-us/library/ms912391%28v=winembedded.11%29.aspx'>
1366 * Microsoft Time Zone Index Values</ulink> for the list of time zones
1369 * You should release the return value by calling g_time_zone_unref()
1370 * when you are done with it.
1372 * Returns: the requested timezone
1377 g_time_zone_new (const gchar *identifier)
1379 GTimeZone *tz = NULL;
1380 TimeZoneRule *rules;
1383 G_LOCK (time_zones);
1384 if (time_zones == NULL)
1385 time_zones = g_hash_table_new (g_str_hash, g_str_equal);
1389 tz = g_hash_table_lookup (time_zones, identifier);
1392 g_atomic_int_inc (&tz->ref_count);
1393 G_UNLOCK (time_zones);
1398 tz = g_slice_new0 (GTimeZone);
1399 tz->name = g_strdup (identifier);
1402 zone_for_constant_offset (tz, identifier);
1404 if (tz->t_info == NULL &&
1405 (rules_num = rules_from_identifier (identifier, &rules)))
1407 init_zone_from_rules (tz, rules, rules_num);
1411 if (tz->t_info == NULL)
1414 GBytes *zoneinfo = zone_info_unix (identifier);
1416 zone_for_constant_offset (tz, "UTC");
1419 init_zone_from_iana_info (tz, zoneinfo);
1420 g_bytes_unref (zoneinfo);
1422 #elif defined (G_OS_WIN32)
1423 if ((rules_num = rules_from_windows_time_zone (identifier, &rules)))
1425 init_zone_from_rules (tz, rules, rules_num);
1430 if (tz->t_info == NULL)
1433 zone_for_constant_offset (tz, "UTC");
1436 TIME_ZONE_INFORMATION tzi;
1438 if (GetTimeZoneInformation (&tzi) != TIME_ZONE_ID_INVALID)
1440 rules = g_new0 (TimeZoneRule, 2);
1442 rule_from_windows_time_zone_info (&rules[0], &tzi);
1444 memset (rules[0].std_name, 0, NAME_SIZE);
1445 memset (rules[0].dlt_name, 0, NAME_SIZE);
1447 rules[0].start_year = MIN_TZYEAR;
1448 rules[1].start_year = MAX_TZYEAR;
1450 init_zone_from_rules (tz, rules, 2);
1458 if (tz->t_info != NULL)
1461 g_hash_table_insert (time_zones, tz->name, tz);
1463 g_atomic_int_inc (&tz->ref_count);
1464 G_UNLOCK (time_zones);
1470 * g_time_zone_new_utc:
1472 * Creates a #GTimeZone corresponding to UTC.
1474 * This is equivalent to calling g_time_zone_new() with a value like
1475 * "Z", "UTC", "+00", etc.
1477 * You should release the return value by calling g_time_zone_unref()
1478 * when you are done with it.
1480 * Returns: the universal timezone
1485 g_time_zone_new_utc (void)
1487 return g_time_zone_new ("UTC");
1491 * g_time_zone_new_local:
1493 * Creates a #GTimeZone corresponding to local time. The local time
1494 * zone may change between invocations to this function; for example,
1495 * if the system administrator changes it.
1497 * This is equivalent to calling g_time_zone_new() with the value of the
1498 * <varname>TZ</varname> environment variable (including the possibility
1501 * You should release the return value by calling g_time_zone_unref()
1502 * when you are done with it.
1504 * Returns: the local timezone
1509 g_time_zone_new_local (void)
1511 return g_time_zone_new (getenv ("TZ"));
1514 #define TRANSITION(n) g_array_index (tz->transitions, Transition, n)
1515 #define TRANSITION_INFO(n) g_array_index (tz->t_info, TransitionInfo, n)
1517 /* Internal helpers {{{1 */
1518 /* NB: Interval 0 is before the first transition, so there's no
1519 * transition structure to point to which TransitionInfo to
1520 * use. Rule-based zones are set up so that TI 0 is always standard
1521 * time (which is what's in effect before Daylight time got started
1522 * in the early 20th century), but IANA tzfiles don't follow that
1523 * convention. The tzfile documentation says to use the first
1524 * standard-time (i.e., non-DST) tinfo, so that's what we do.
1526 inline static const TransitionInfo*
1527 interval_info (GTimeZone *tz,
1531 g_return_val_if_fail (tz->t_info != NULL, NULL);
1532 if (interval && tz->transitions && interval <= tz->transitions->len)
1533 index = (TRANSITION(interval - 1)).info_index;
1536 for (index = 0; index < tz->t_info->len; index++)
1538 TransitionInfo *tzinfo = &(TRANSITION_INFO(index));
1539 if (!tzinfo->is_dst)
1545 return &(TRANSITION_INFO(index));
1548 inline static gint64
1549 interval_start (GTimeZone *tz,
1552 if (!interval || tz->transitions == NULL || tz->transitions->len == 0)
1554 if (interval > tz->transitions->len)
1555 interval = tz->transitions->len;
1556 return (TRANSITION(interval - 1)).time;
1559 inline static gint64
1560 interval_end (GTimeZone *tz,
1563 if (tz->transitions && interval < tz->transitions->len)
1564 return (TRANSITION(interval)).time - 1;
1568 inline static gint32
1569 interval_offset (GTimeZone *tz,
1572 g_return_val_if_fail (tz->t_info != NULL, 0);
1573 return interval_info (tz, interval)->gmt_offset;
1576 inline static gboolean
1577 interval_isdst (GTimeZone *tz,
1580 g_return_val_if_fail (tz->t_info != NULL, 0);
1581 return interval_info (tz, interval)->is_dst;
1585 inline static gboolean
1586 interval_isgmt (GTimeZone *tz,
1589 g_return_val_if_fail (tz->t_info != NULL, 0);
1590 return interval_info (tz, interval)->is_gmt;
1593 inline static gboolean
1594 interval_isstandard (GTimeZone *tz,
1597 return interval_info (tz, interval)->is_standard;
1600 inline static gchar*
1601 interval_abbrev (GTimeZone *tz,
1604 g_return_val_if_fail (tz->t_info != NULL, 0);
1605 return interval_info (tz, interval)->abbrev;
1608 inline static gint64
1609 interval_local_start (GTimeZone *tz,
1613 return interval_start (tz, interval) + interval_offset (tz, interval);
1618 inline static gint64
1619 interval_local_end (GTimeZone *tz,
1622 if (tz->transitions && interval < tz->transitions->len)
1623 return interval_end (tz, interval) + interval_offset (tz, interval);
1629 interval_valid (GTimeZone *tz,
1632 if ( tz->transitions == NULL)
1633 return interval == 0;
1634 return interval <= tz->transitions->len;
1637 /* g_time_zone_find_interval() {{{1 */
1640 * g_time_zone_adjust_time:
1642 * @type: the #GTimeType of @time_
1643 * @time_: a pointer to a number of seconds since January 1, 1970
1645 * Finds an interval within @tz that corresponds to the given @time_,
1646 * possibly adjusting @time_ if required to fit into an interval.
1647 * The meaning of @time_ depends on @type.
1649 * This function is similar to g_time_zone_find_interval(), with the
1650 * difference that it always succeeds (by making the adjustments
1653 * In any of the cases where g_time_zone_find_interval() succeeds then
1654 * this function returns the same value, without modifying @time_.
1656 * This function may, however, modify @time_ in order to deal with
1657 * non-existent times. If the non-existent local @time_ of 02:30 were
1658 * requested on March 14th 2010 in Toronto then this function would
1659 * adjust @time_ to be 03:00 and return the interval containing the
1662 * Returns: the interval containing @time_, never -1
1667 g_time_zone_adjust_time (GTimeZone *tz,
1674 if (tz->transitions == NULL)
1677 intervals = tz->transitions->len;
1679 /* find the interval containing *time UTC
1680 * TODO: this could be binary searched (or better) */
1681 for (i = 0; i <= intervals; i++)
1682 if (*time_ <= interval_end (tz, i))
1685 g_assert (interval_start (tz, i) <= *time_ && *time_ <= interval_end (tz, i));
1687 if (type != G_TIME_TYPE_UNIVERSAL)
1689 if (*time_ < interval_local_start (tz, i))
1690 /* if time came before the start of this interval... */
1694 /* if it's not in the previous interval... */
1695 if (*time_ > interval_local_end (tz, i))
1697 /* it doesn't exist. fast-forward it. */
1699 *time_ = interval_local_start (tz, i);
1703 else if (*time_ > interval_local_end (tz, i))
1704 /* if time came after the end of this interval... */
1708 /* if it's not in the next interval... */
1709 if (*time_ < interval_local_start (tz, i))
1710 /* it doesn't exist. fast-forward it. */
1711 *time_ = interval_local_start (tz, i);
1714 else if (interval_isdst (tz, i) != type)
1715 /* it's in this interval, but dst flag doesn't match.
1716 * check neighbours for a better fit. */
1718 if (i && *time_ <= interval_local_end (tz, i - 1))
1721 else if (i < intervals &&
1722 *time_ >= interval_local_start (tz, i + 1))
1731 * g_time_zone_find_interval:
1733 * @type: the #GTimeType of @time_
1734 * @time_: a number of seconds since January 1, 1970
1736 * Finds an the interval within @tz that corresponds to the given @time_.
1737 * The meaning of @time_ depends on @type.
1739 * If @type is %G_TIME_TYPE_UNIVERSAL then this function will always
1740 * succeed (since universal time is monotonic and continuous).
1742 * Otherwise @time_ is treated is local time. The distinction between
1743 * %G_TIME_TYPE_STANDARD and %G_TIME_TYPE_DAYLIGHT is ignored except in
1744 * the case that the given @time_ is ambiguous. In Toronto, for example,
1745 * 01:30 on November 7th 2010 occurred twice (once inside of daylight
1746 * savings time and the next, an hour later, outside of daylight savings
1747 * time). In this case, the different value of @type would result in a
1748 * different interval being returned.
1750 * It is still possible for this function to fail. In Toronto, for
1751 * example, 02:00 on March 14th 2010 does not exist (due to the leap
1752 * forward to begin daylight savings time). -1 is returned in that
1755 * Returns: the interval containing @time_, or -1 in case of failure
1760 g_time_zone_find_interval (GTimeZone *tz,
1767 if (tz->transitions == NULL)
1769 intervals = tz->transitions->len;
1770 for (i = 0; i <= intervals; i++)
1771 if (time_ <= interval_end (tz, i))
1774 if (type == G_TIME_TYPE_UNIVERSAL)
1777 if (time_ < interval_local_start (tz, i))
1779 if (time_ > interval_local_end (tz, --i))
1783 else if (time_ > interval_local_end (tz, i))
1785 if (time_ < interval_local_start (tz, ++i))
1789 else if (interval_isdst (tz, i) != type)
1791 if (i && time_ <= interval_local_end (tz, i - 1))
1794 else if (i < intervals && time_ >= interval_local_start (tz, i + 1))
1801 /* Public API accessors {{{1 */
1804 * g_time_zone_get_abbreviation:
1806 * @interval: an interval within the timezone
1808 * Determines the time zone abbreviation to be used during a particular
1809 * @interval of time in the time zone @tz.
1811 * For example, in Toronto this is currently "EST" during the winter
1812 * months and "EDT" during the summer months when daylight savings time
1815 * Returns: the time zone abbreviation, which belongs to @tz
1820 g_time_zone_get_abbreviation (GTimeZone *tz,
1823 g_return_val_if_fail (interval_valid (tz, (guint)interval), NULL);
1825 return interval_abbrev (tz, (guint)interval);
1829 * g_time_zone_get_offset:
1831 * @interval: an interval within the timezone
1833 * Determines the offset to UTC in effect during a particular @interval
1834 * of time in the time zone @tz.
1836 * The offset is the number of seconds that you add to UTC time to
1837 * arrive at local time for @tz (ie: negative numbers for time zones
1838 * west of GMT, positive numbers for east).
1840 * Returns: the number of seconds that should be added to UTC to get the
1846 g_time_zone_get_offset (GTimeZone *tz,
1849 g_return_val_if_fail (interval_valid (tz, (guint)interval), 0);
1851 return interval_offset (tz, (guint)interval);
1855 * g_time_zone_is_dst:
1857 * @interval: an interval within the timezone
1859 * Determines if daylight savings time is in effect during a particular
1860 * @interval of time in the time zone @tz.
1862 * Returns: %TRUE if daylight savings time is in effect
1867 g_time_zone_is_dst (GTimeZone *tz,
1870 g_return_val_if_fail (interval_valid (tz, interval), FALSE);
1872 if (tz->transitions == NULL)
1875 return interval_isdst (tz, (guint)interval);
1879 /* vim:set foldmethod=marker: */