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, see <http://www.gnu.org/licenses/>.
17 * Author: Ryan Lortie <desrt@desrt.ca>
24 #include "gtimezone.h"
30 #include "gmappedfile.h"
31 #include "gtestutils.h"
32 #include "gfileutils.h"
33 #include "gstrfuncs.h"
38 #include "gdatetime.h"
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 * A time zone contains a number of intervals. Each interval has
56 * an abbreviation to describe it, an offet to UTC and a flag indicating
57 * if the daylight savings time is in effect during that interval. A
58 * time zone always has at least one interval -- interval 0.
60 * Every UTC time is contained within exactly one interval, but a given
61 * local time may be contained within zero, one or two intervals (due to
62 * incontinuities associated with daylight savings time).
64 * An interval may refer to a specific period of time (eg: the duration
65 * of daylight savings time during 2010) or it may refer to many periods
66 * of time that share the same properties (eg: all periods of daylight
67 * savings time). It is also possible (usually for political reasons)
68 * that some properties (like the abbreviation) change between intervals
69 * without other properties changing.
71 * #GTimeZone is available since GLib 2.26.
77 * #GTimeZone is an opaque structure whose members cannot be accessed
83 /* IANA zoneinfo file format {{{1 */
86 typedef struct { gchar bytes[8]; } gint64_be;
87 typedef struct { gchar bytes[4]; } gint32_be;
88 typedef struct { gchar bytes[4]; } guint32_be;
90 static inline gint64 gint64_from_be (const gint64_be be) {
91 gint64 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT64_FROM_BE (tmp);
94 static inline gint32 gint32_from_be (const gint32_be be) {
95 gint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT32_FROM_BE (tmp);
98 static inline guint32 guint32_from_be (const guint32_be be) {
99 guint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GUINT32_FROM_BE (tmp);
102 /* The layout of an IANA timezone file header */
107 guchar tzh_reserved[15];
109 guint32_be tzh_ttisgmtcnt;
110 guint32_be tzh_ttisstdcnt;
111 guint32_be tzh_leapcnt;
112 guint32_be tzh_timecnt;
113 guint32_be tzh_typecnt;
114 guint32_be tzh_charcnt;
124 /* A Transition Date structure for TZ Rules, an intermediate structure
125 for parsing MSWindows and Environment-variable time zones. It
126 Generalizes MSWindows's SYSTEMTIME struct.
140 /* POSIX Timezone abbreviations are typically 3 or 4 characters, but
141 Microsoft uses 32-character names. We'll use one larger to ensure
142 we have room for the terminating \0.
146 /* A MSWindows-style time zone transition rule. Generalizes the
147 MSWindows TIME_ZONE_INFORMATION struct. Also used to compose time
148 zones from tzset-style identifiers.
155 TimeZoneDate dlt_start;
156 TimeZoneDate dlt_end;
157 gchar std_name[NAME_SIZE];
158 gchar dlt_name[NAME_SIZE];
161 /* GTimeZone's internal representation of a Daylight Savings (Summer)
168 gboolean is_standard;
173 /* GTimeZone's representation of a transition time to or from Daylight
174 Savings (Summer) time and Standard time for the zone. */
181 /* GTimeZone structure */
185 GArray *t_info; /* Array of TransitionInfo */
186 GArray *transitions; /* Array of Transition */
190 G_LOCK_DEFINE_STATIC (time_zones);
191 static GHashTable/*<string?, GTimeZone>*/ *time_zones;
193 #define MIN_TZYEAR 1916 /* Daylight Savings started in WWI */
194 #define MAX_TZYEAR 2999 /* And it's not likely ever to go away, but
195 there's no point in getting carried
202 * Decreases the reference count on @tz.
207 g_time_zone_unref (GTimeZone *tz)
212 ref_count = g_atomic_int_get (&tz->ref_count);
214 g_assert (ref_count > 0);
218 if (tz->name != NULL)
222 /* someone else might have grabbed a ref in the meantime */
223 if G_UNLIKELY (g_atomic_int_get (&tz->ref_count) != 1)
225 G_UNLOCK(time_zones);
229 g_hash_table_remove (time_zones, tz->name);
230 G_UNLOCK(time_zones);
233 if (tz->t_info != NULL)
236 for (idx = 0; idx < tz->t_info->len; idx++)
238 TransitionInfo *info = &g_array_index (tz->t_info, TransitionInfo, idx);
239 g_free (info->abbrev);
241 g_array_free (tz->t_info, TRUE);
243 if (tz->transitions != NULL)
244 g_array_free (tz->transitions, TRUE);
247 g_slice_free (GTimeZone, tz);
250 else if G_UNLIKELY (!g_atomic_int_compare_and_exchange (&tz->ref_count,
260 * Increases the reference count on @tz.
262 * Returns: a new reference to @tz.
267 g_time_zone_ref (GTimeZone *tz)
269 g_assert (tz->ref_count > 0);
271 g_atomic_int_inc (&tz->ref_count);
276 /* fake zoneinfo creation (for RFC3339/ISO 8601 timezones) {{{1 */
278 * parses strings of the form h or hh[[:]mm[[[:]ss]]] where:
284 parse_time (const gchar *time_,
287 if (*time_ < '0' || '9' < *time_)
290 *offset = 60 * 60 * (*time_++ - '0');
297 if (*time_ < '0' || '9' < *time_)
301 *offset += 60 * 60 * (*time_++ - '0');
303 if (*offset > 23 * 60 * 60)
313 if (*time_ < '0' || '5' < *time_)
316 *offset += 10 * 60 * (*time_++ - '0');
318 if (*time_ < '0' || '9' < *time_)
321 *offset += 60 * (*time_++ - '0');
329 if (*time_ < '0' || '5' < *time_)
332 *offset += 10 * (*time_++ - '0');
334 if (*time_ < '0' || '9' < *time_)
337 *offset += *time_++ - '0';
339 return *time_ == '\0';
343 parse_constant_offset (const gchar *name,
346 if (g_strcmp0 (name, "UTC") == 0)
352 if (*name >= '0' && '9' >= *name)
353 return parse_time (name, offset);
362 return parse_time (name, offset);
365 if (parse_time (name, offset))
377 zone_for_constant_offset (GTimeZone *gtz, const gchar *name)
382 if (name == NULL || !parse_constant_offset (name, &offset))
385 info.gmt_offset = offset;
387 info.is_standard = TRUE;
389 info.abbrev = g_strdup (name);
392 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), 1);
393 g_array_append_val (gtz->t_info, info);
395 /* Constant offset, no transitions */
396 gtz->transitions = NULL;
401 zone_info_unix (const gchar *identifier)
404 GMappedFile *file = NULL;
405 GBytes *zoneinfo = NULL;
407 /* identifier can be a relative or absolute path name;
408 if relative, it is interpreted starting from /usr/share/zoneinfo
409 while the POSIX standard says it should start with :,
410 glibc allows both syntaxes, so we should too */
411 if (identifier != NULL)
415 tzdir = getenv ("TZDIR");
417 tzdir = "/usr/share/zoneinfo";
419 if (*identifier == ':')
422 if (g_path_is_absolute (identifier))
423 filename = g_strdup (identifier);
425 filename = g_build_filename (tzdir, identifier, NULL);
428 filename = g_strdup ("/etc/localtime");
430 file = g_mapped_file_new (filename, FALSE, NULL);
433 zoneinfo = g_bytes_new_with_free_func (g_mapped_file_get_contents (file),
434 g_mapped_file_get_length (file),
435 (GDestroyNotify)g_mapped_file_unref,
436 g_mapped_file_ref (file));
437 g_mapped_file_unref (file);
444 init_zone_from_iana_info (GTimeZone *gtz, GBytes *zoneinfo)
448 guint32 time_count, type_count, leap_count, isgmt_count;
449 guint32 isstd_count, char_count ;
450 guint8 *tz_transitions, *tz_type_index, *tz_ttinfo;
451 guint8 *tz_leaps, *tz_isgmt, *tz_isstd;
453 gsize timesize = sizeof (gint32), countsize = sizeof (gint32);
454 const struct tzhead *header = g_bytes_get_data (zoneinfo, &size);
456 g_return_if_fail (size >= sizeof (struct tzhead) &&
457 memcmp (header, "TZif", 4) == 0);
459 if (header->tzh_version == '2')
461 /* Skip ahead to the newer 64-bit data if it's available. */
462 header = (const struct tzhead *)
463 (((const gchar *) (header + 1)) +
464 guint32_from_be(header->tzh_ttisgmtcnt) +
465 guint32_from_be(header->tzh_ttisstdcnt) +
466 8 * guint32_from_be(header->tzh_leapcnt) +
467 5 * guint32_from_be(header->tzh_timecnt) +
468 6 * guint32_from_be(header->tzh_typecnt) +
469 guint32_from_be(header->tzh_charcnt));
470 timesize = sizeof (gint64);
472 time_count = guint32_from_be(header->tzh_timecnt);
473 type_count = guint32_from_be(header->tzh_typecnt);
474 leap_count = guint32_from_be(header->tzh_leapcnt);
475 isgmt_count = guint32_from_be(header->tzh_ttisgmtcnt);
476 isstd_count = guint32_from_be(header->tzh_ttisstdcnt);
477 char_count = guint32_from_be(header->tzh_charcnt);
479 g_assert (type_count == isgmt_count);
480 g_assert (type_count == isstd_count);
482 tz_transitions = ((guint8 *) (header) + sizeof (*header));
483 tz_type_index = tz_transitions + timesize * time_count;
484 tz_ttinfo = tz_type_index + time_count;
485 tz_abbrs = tz_ttinfo + sizeof (struct ttinfo) * type_count;
486 tz_leaps = tz_abbrs + char_count;
487 tz_isstd = tz_leaps + (timesize + countsize) * leap_count;
488 tz_isgmt = tz_isstd + isstd_count;
490 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo),
492 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition),
495 for (index = 0; index < type_count; index++)
497 TransitionInfo t_info;
498 struct ttinfo info = ((struct ttinfo*)tz_ttinfo)[index];
499 t_info.gmt_offset = gint32_from_be (info.tt_gmtoff);
500 t_info.is_dst = info.tt_isdst ? TRUE : FALSE;
501 t_info.is_standard = tz_isstd[index] ? TRUE : FALSE;
502 t_info.is_gmt = tz_isgmt[index] ? TRUE : FALSE;
503 t_info.abbrev = g_strdup ((gchar *) &tz_abbrs[info.tt_abbrind]);
504 g_array_append_val (gtz->t_info, t_info);
507 for (index = 0; index < time_count; index++)
510 if (header->tzh_version == '2')
511 trans.time = gint64_from_be (((gint64_be*)tz_transitions)[index]);
513 trans.time = gint32_from_be (((gint32_be*)tz_transitions)[index]);
514 trans.info_index = tz_type_index[index];
515 g_assert (trans.info_index >= 0);
516 g_assert (trans.info_index < gtz->t_info->len);
517 g_array_append_val (gtz->transitions, trans);
521 #elif defined (G_OS_WIN32)
524 copy_windows_systemtime (SYSTEMTIME *s_time, TimeZoneDate *tzdate)
526 tzdate->sec = s_time->wSecond;
527 tzdate->min = s_time->wMinute;
528 tzdate->hour = s_time->wHour;
529 tzdate->mon = s_time->wMonth;
530 tzdate->year = s_time->wYear;
531 tzdate->wday = s_time->wDayOfWeek ? s_time->wDayOfWeek : 7;
535 tzdate->mday = s_time->wDay;
539 tzdate->week = s_time->wDay;
542 /* UTC = local time + bias while local time = UTC + offset */
544 rule_from_windows_time_zone_info (TimeZoneRule *rule,
545 TIME_ZONE_INFORMATION *tzi)
548 if (tzi->StandardDate.wMonth)
550 rule->std_offset = -(tzi->Bias + tzi->StandardBias) * 60;
551 rule->dlt_offset = -(tzi->Bias + tzi->DaylightBias) * 60;
552 copy_windows_systemtime (&(tzi->DaylightDate), &(rule->dlt_start));
554 copy_windows_systemtime (&(tzi->StandardDate), &(rule->dlt_end));
560 rule->std_offset = -tzi->Bias * 60;
561 rule->dlt_start.mon = 0;
563 strncpy (rule->std_name, (gchar*)tzi->StandardName, NAME_SIZE - 1);
564 strncpy (rule->dlt_name, (gchar*)tzi->DaylightName, NAME_SIZE - 1);
568 windows_default_tzname (void)
570 const gchar *subkey =
571 "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation";
573 gchar *key_name = NULL;
574 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
575 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
578 if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
579 NULL, &size) == ERROR_SUCCESS)
581 key_name = g_malloc ((gint)size);
582 if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
583 (LPBYTE)key_name, &size) != ERROR_SUCCESS)
599 SYSTEMTIME StandardDate;
600 SYSTEMTIME DaylightDate;
604 system_time_copy (SYSTEMTIME *orig, SYSTEMTIME *target)
606 g_return_if_fail (orig != NULL);
607 g_return_if_fail (target != NULL);
609 target->wYear = orig->wYear;
610 target->wMonth = orig->wMonth;
611 target->wDayOfWeek = orig->wDayOfWeek;
612 target->wDay = orig->wDay;
613 target->wHour = orig->wHour;
614 target->wMinute = orig->wMinute;
615 target->wSecond = orig->wSecond;
616 target->wMilliseconds = orig->wMilliseconds;
620 register_tzi_to_tzi (RegTZI *reg, TIME_ZONE_INFORMATION *tzi)
622 g_return_if_fail (reg != NULL);
623 g_return_if_fail (tzi != NULL);
624 tzi->Bias = reg->Bias;
625 system_time_copy (&(reg->StandardDate), &(tzi->StandardDate));
626 tzi->StandardBias = reg->StandardBias;
627 system_time_copy (&(reg->DaylightDate), &(tzi->DaylightDate));
628 tzi->DaylightBias = reg->DaylightBias;
632 rules_from_windows_time_zone (const gchar *identifier, TimeZoneRule **rules)
635 gchar *subkey, *subkey_dynamic;
636 gchar *key_name = NULL;
637 const gchar *reg_key =
638 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\";
639 TIME_ZONE_INFORMATION tzi;
642 RegTZI regtzi, regtzi_prev;
648 key_name = windows_default_tzname ();
650 key_name = g_strdup (identifier);
655 subkey = g_strconcat (reg_key, key_name, NULL);
656 subkey_dynamic = g_strconcat (subkey, "\\Dynamic DST", NULL);
658 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
659 KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
661 size = sizeof tzi.StandardName;
662 if (RegQueryValueExA (key, "Std", NULL, NULL,
663 (LPBYTE)&(tzi.StandardName), &size) != ERROR_SUCCESS)
666 size = sizeof tzi.DaylightName;
668 if (RegQueryValueExA (key, "Dlt", NULL, NULL,
669 (LPBYTE)&(tzi.DaylightName), &size) != ERROR_SUCCESS)
673 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey_dynamic, 0,
674 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
681 if (RegQueryValueExA (key, "FirstEntry", NULL, NULL,
682 (LPBYTE) &first, &size) != ERROR_SUCCESS)
686 if (RegQueryValueExA (key, "LastEntry", NULL, NULL,
687 (LPBYTE) &last, &size) != ERROR_SUCCESS)
690 rules_num = last - first + 2;
691 *rules = g_new0 (TimeZoneRule, rules_num);
693 for (year = first, i = 0; year <= last; year++)
695 s = g_strdup_printf ("%d", year);
697 size = sizeof regtzi;
698 if (RegQueryValueExA (key, s, NULL, NULL,
699 (LPBYTE) ®tzi, &size) != ERROR_SUCCESS)
708 if (year > first && memcmp (®tzi_prev, ®tzi, sizeof regtzi) == 0)
711 memcpy (®tzi_prev, ®tzi, sizeof regtzi);
713 register_tzi_to_tzi (®tzi, &tzi);
714 rule_from_windows_time_zone_info (&(*rules)[i], &tzi);
715 (*rules)[i++].start_year = year;
723 else if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
724 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
726 size = sizeof regtzi;
727 if (RegQueryValueExA (key, "TZI", NULL, NULL,
728 (LPBYTE) ®tzi, &size) == ERROR_SUCCESS)
731 *rules = g_new0 (TimeZoneRule, 2);
732 register_tzi_to_tzi (®tzi, &tzi);
733 rule_from_windows_time_zone_info (&(*rules)[0], &tzi);
739 g_free (subkey_dynamic);
745 (*rules)[0].start_year = MIN_TZYEAR;
746 if ((*rules)[rules_num - 2].start_year < MAX_TZYEAR)
747 (*rules)[rules_num - 1].start_year = MAX_TZYEAR;
749 (*rules)[rules_num - 1].start_year = (*rules)[rules_num - 2].start_year + 1;
760 find_relative_date (TimeZoneDate *buffer)
764 g_date_clear (&date, 1);
767 /* Get last day if last is needed, first day otherwise */
768 if (buffer->mon == 13 || buffer->mon == 14) /* Julian Date */
770 g_date_set_dmy (&date, 1, 1, buffer->year);
771 if (wday >= 59 && buffer->mon == 13 && g_date_is_leap_year (buffer->year))
772 g_date_add_days (&date, wday);
774 g_date_add_days (&date, wday - 1);
775 buffer->mon = (int) g_date_get_month (&date);
776 buffer->mday = (int) g_date_get_day (&date);
782 guint days_in_month = g_date_days_in_month (buffer->mon, buffer->year);
783 GDateWeekday first_wday;
785 g_date_set_dmy (&date, 1, buffer->mon, buffer->year);
786 first_wday = g_date_get_weekday (&date);
788 if (first_wday > wday)
790 /* week is 1 <= w <= 5, we need 0-based */
791 days = 7 * (buffer->week - 1) + wday - first_wday;
793 while (days > days_in_month)
796 g_date_add_days (&date, days);
798 buffer->mday = g_date_get_day (&date);
802 /* Offset is previous offset of local time. Returns 0 if month is 0 */
804 boundary_for_year (TimeZoneDate *boundary,
810 const guint64 unix_epoch_start = 719163L;
811 const guint64 seconds_per_day = 86400L;
817 if (boundary->year == 0)
822 find_relative_date (&buffer);
825 g_assert (buffer.year == year);
826 g_date_clear (&date, 1);
827 g_date_set_dmy (&date, buffer.mday, buffer.mon, buffer.year);
828 return ((g_date_get_julian (&date) - unix_epoch_start) * seconds_per_day +
829 buffer.hour * 3600 + buffer.min * 60 + buffer.sec - offset);
833 fill_transition_info_from_rule (TransitionInfo *info,
837 gint offset = is_dst ? rule->dlt_offset : rule->std_offset;
838 gchar *name = is_dst ? rule->dlt_name : rule->std_name;
840 info->gmt_offset = offset;
841 info->is_dst = is_dst;
842 info->is_standard = FALSE;
843 info->is_gmt = FALSE;
846 info->abbrev = g_strdup (name);
849 info->abbrev = g_strdup_printf ("%+03d%02d",
851 (int) abs (offset / 60) % 60);
855 init_zone_from_rules (GTimeZone *gtz,
859 guint type_count = 0, trans_count = 0, info_index = 0;
860 guint ri; /* rule index */
861 gboolean skip_first_std_trans = TRUE;
867 /* Last rule only contains max year */
868 for (ri = 0; ri < rules_num - 1; ri++)
870 if (rules[ri].dlt_start.mon || rules[ri].dlt_end.mon)
872 guint rulespan = (rules[ri + 1].start_year - rules[ri].start_year);
873 guint transitions = rules[ri].dlt_start.mon > 0 ? 1 : 0;
874 transitions += rules[ri].dlt_end.mon > 0 ? 1 : 0;
875 type_count += rules[ri].dlt_start.mon > 0 ? 2 : 1;
876 trans_count += transitions * rulespan;
882 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), type_count);
883 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition), trans_count);
885 last_offset = rules[0].std_offset;
887 for (ri = 0; ri < rules_num - 1; ri++)
889 if ((rules[ri].std_offset || rules[ri].dlt_offset) &&
890 rules[ri].dlt_start.mon == 0 && rules[ri].dlt_end.mon == 0)
892 TransitionInfo std_info;
894 fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
895 g_array_append_val (gtz->t_info, std_info);
898 ((rules[ri - 1].dlt_start.mon > 12 &&
899 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
900 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
902 /* The previous rule was a southern hemisphere rule that
903 starts the year with DST, so we need to add a
904 transition to return to standard time */
905 guint year = rules[ri].start_year;
906 gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
908 Transition std_trans = {std_time, info_index};
909 g_array_append_val (gtz->transitions, std_trans);
912 last_offset = rules[ri].std_offset;
914 skip_first_std_trans = TRUE;
916 else if (rules[ri].std_offset || rules[ri].dlt_offset)
918 const guint start_year = rules[ri].start_year;
919 const guint end_year = rules[ri + 1].start_year;
922 TransitionInfo std_info, dlt_info;
923 if (rules[ri].dlt_start.mon > 12)
924 dlt_first = rules[ri].dlt_start.wday > rules[ri].dlt_end.wday;
926 dlt_first = rules[ri].dlt_start.mon > rules[ri].dlt_end.mon;
927 /* Standard rules are always even, because before the first
928 transition is always standard time, and 0 is even. */
929 fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
930 fill_transition_info_from_rule (&dlt_info, &(rules[ri]), TRUE);
932 g_array_append_val (gtz->t_info, std_info);
933 g_array_append_val (gtz->t_info, dlt_info);
935 /* Transition dates. We hope that a year which ends daylight
936 time in a southern-hemisphere country (i.e., one that
937 begins the year in daylight time) will include a rule
938 which has only a dlt_end. */
939 for (year = start_year; year < end_year; year++)
941 gint32 dlt_offset = (dlt_first ? last_offset :
942 rules[ri].dlt_offset);
943 gint32 std_offset = (dlt_first ? rules[ri].std_offset :
945 /* NB: boundary_for_year returns 0 if mon == 0 */
946 gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
948 gint64 dlt_time = boundary_for_year (&rules[ri].dlt_start,
950 Transition std_trans = {std_time, info_index};
951 Transition dlt_trans = {dlt_time, info_index + 1};
952 last_offset = (dlt_first ? rules[ri].dlt_offset :
953 rules[ri].std_offset);
956 if (skip_first_std_trans)
957 skip_first_std_trans = FALSE;
959 g_array_append_val (gtz->transitions, std_trans);
961 g_array_append_val (gtz->transitions, dlt_trans);
966 g_array_append_val (gtz->transitions, dlt_trans);
968 g_array_append_val (gtz->transitions, std_trans);
976 ((rules[ri - 1].dlt_start.mon > 12 &&
977 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
978 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
980 /* The previous rule was a southern hemisphere rule that
981 starts the year with DST, so we need to add a
982 transition to return to standard time */
984 guint year = rules[ri].start_year;
986 fill_transition_info_from_rule (&info, &(rules[ri - 1]), FALSE);
987 g_array_append_val (gtz->t_info, info);
988 trans.time = boundary_for_year (&rules[ri - 1].dlt_end,
990 trans.info_index = info_index;
991 g_array_append_val (gtz->transitions, trans);
996 * parses date[/time] for parsing TZ environment variable
998 * date is either Mm.w.d, Jn or N
1005 * time is either h or hh[[:]mm[[[:]ss]]]
1011 parse_mwd_boundary (gchar **pos, TimeZoneDate *boundary)
1013 gint month, week, day;
1015 if (**pos == '\0' || **pos < '0' || '9' < **pos)
1018 month = *(*pos)++ - '0';
1020 if ((month == 1 && **pos >= '0' && '2' >= **pos) ||
1021 (month == 0 && **pos >= '0' && '9' >= **pos))
1024 month += *(*pos)++ - '0';
1027 if (*(*pos)++ != '.' || month == 0)
1030 if (**pos == '\0' || **pos < '1' || '5' < **pos)
1033 week = *(*pos)++ - '0';
1035 if (*(*pos)++ != '.')
1038 if (**pos == '\0' || **pos < '0' || '6' < **pos)
1041 day = *(*pos)++ - '0';
1047 boundary->mon = month;
1048 boundary->week = week;
1049 boundary->wday = day;
1053 /* Different implementations of tzset interpret the Julian day field
1054 differently. For example, Linux specifies that it should be 1-based
1055 (1 Jan is JD 1) for both Jn and n formats, while zOS and BSD
1056 specify that a Jn JD is 1-based while an n JD is 0-based. Rather
1057 than trying to follow different specs, we will follow GDate's
1058 practice thatIn order to keep it simple, we will follow Linux's
1062 parse_julian_boundary (gchar** pos, TimeZoneDate *boundary,
1063 gboolean ignore_leap)
1068 while (**pos >= '0' && '9' >= **pos)
1071 day += *(*pos)++ - '0';
1074 if (day < 1 || 365 < day)
1077 g_date_clear (&date, 1);
1078 g_date_set_julian (&date, day);
1080 boundary->mon = (int) g_date_get_month (&date);
1081 boundary->mday = (int) g_date_get_day (&date);
1084 if (!ignore_leap && day >= 59)
1091 parse_tz_boundary (const gchar *identifier,
1092 TimeZoneDate *boundary)
1096 pos = (gchar*)identifier;
1097 /* Month-week-weekday */
1101 if (!parse_mwd_boundary (&pos, boundary))
1104 /* Julian date which ignores Feb 29 in leap years */
1105 else if (*pos == 'J')
1108 if (!parse_julian_boundary (&pos, boundary, FALSE))
1111 /* Julian date which counts Feb 29 in leap years */
1112 else if (*pos >= '0' && '9' >= *pos)
1114 if (!parse_julian_boundary (&pos, boundary, TRUE))
1126 if (!parse_time (++pos, &offset))
1129 boundary->hour = offset / 3600;
1130 boundary->min = (offset / 60) % 60;
1131 boundary->sec = offset % 3600;
1142 return *pos == '\0';
1147 create_ruleset_from_rule (TimeZoneRule **rules, TimeZoneRule *rule)
1149 *rules = g_new0 (TimeZoneRule, 2);
1151 (*rules)[0].start_year = MIN_TZYEAR;
1152 (*rules)[1].start_year = MAX_TZYEAR;
1154 (*rules)[0].std_offset = -rule->std_offset;
1155 (*rules)[0].dlt_offset = -rule->dlt_offset;
1156 (*rules)[0].dlt_start = rule->dlt_start;
1157 (*rules)[0].dlt_end = rule->dlt_end;
1158 strcpy ((*rules)[0].std_name, rule->std_name);
1159 strcpy ((*rules)[0].dlt_name, rule->dlt_name);
1164 parse_offset (gchar **pos, gint32 *target)
1167 gchar *target_pos = *pos;
1170 while (**pos == '+' || **pos == '-' || **pos == ':' ||
1171 (**pos >= '0' && '9' >= **pos))
1174 buffer = g_strndup (target_pos, *pos - target_pos);
1175 ret = parse_constant_offset (buffer, target);
1182 parse_identifier_boundary (gchar **pos, TimeZoneDate *target)
1185 gchar *target_pos = *pos;
1188 while (**pos != ',' && **pos != '\0')
1190 buffer = g_strndup (target_pos, *pos - target_pos);
1191 ret = parse_tz_boundary (buffer, target);
1198 set_tz_name (gchar **pos, gchar *buffer, guint size)
1200 gchar *name_pos = *pos;
1203 /* Name is ASCII alpha (Is this necessarily true?) */
1204 while (g_ascii_isalpha (**pos))
1207 /* Name should be three or more alphabetic characters */
1208 if (*pos - name_pos < 3)
1211 memset (buffer, 0, NAME_SIZE);
1212 /* name_pos isn't 0-terminated, so we have to limit the length expressly */
1213 len = *pos - name_pos > size - 1 ? size - 1 : *pos - name_pos;
1214 strncpy (buffer, name_pos, len);
1219 parse_identifier_boundaries (gchar **pos, TimeZoneRule *tzr)
1221 if (*(*pos)++ != ',')
1225 if (!parse_identifier_boundary (pos, &(tzr->dlt_start)) || *(*pos)++ != ',')
1229 if (!parse_identifier_boundary (pos, &(tzr->dlt_end)))
1235 * Creates an array of TimeZoneRule from a TZ environment variable
1236 * type of identifier. Should free rules afterwards
1239 rules_from_identifier (const gchar *identifier,
1240 TimeZoneRule **rules)
1248 pos = (gchar*)identifier;
1249 memset (&tzr, 0, sizeof (tzr));
1250 /* Standard offset */
1251 if (!(set_tz_name (&pos, tzr.std_name, NAME_SIZE)) ||
1252 !parse_offset (&pos, &(tzr.std_offset)))
1256 return create_ruleset_from_rule (rules, &tzr);
1259 if (!(set_tz_name (&pos, tzr.dlt_name, NAME_SIZE)))
1261 parse_offset (&pos, &(tzr.dlt_offset));
1262 if (tzr.dlt_offset == 0) /* No daylight offset given, assume it's 1
1263 hour earlier that standard */
1264 tzr.dlt_offset = tzr.std_offset - 3600;
1267 /* Windows allows us to use the US DST boundaries if they're not given */
1270 guint rules_num = 0;
1272 /* Use US rules, Windows' default is Pacific Standard Time */
1273 if ((rules_num = rules_from_windows_time_zone ("Pacific Standard Time",
1276 for (i = 0; i < rules_num - 1; i++)
1278 (*rules)[i].std_offset = - tzr.std_offset;
1279 (*rules)[i].dlt_offset = - tzr.dlt_offset;
1280 strcpy ((*rules)[i].std_name, tzr.std_name);
1281 strcpy ((*rules)[i].dlt_name, tzr.dlt_name);
1292 /* Start and end required (format 2) */
1293 if (!parse_identifier_boundaries (&pos, &tzr))
1296 return create_ruleset_from_rule (rules, &tzr);
1299 /* Construction {{{1 */
1302 * @identifier: (allow-none): a timezone identifier
1304 * Creates a #GTimeZone corresponding to @identifier.
1306 * @identifier can either be an RFC3339/ISO 8601 time offset or
1307 * something that would pass as a valid value for the `TZ` environment
1308 * variable (including %NULL).
1310 * In Windows, @identifier can also be the unlocalized name of a time
1311 * zone for standard time, for example "Pacific Standard Time".
1313 * Valid RFC3339 time offsets are <literal>"Z"</literal> (for UTC) or
1314 * <literal>"±hh:mm"</literal>. ISO 8601 additionally specifies
1315 * <literal>"±hhmm"</literal> and <literal>"±hh"</literal>. Offsets are
1316 * time values to be added to Coordinated Universal Time (UTC) to get
1319 * In UNIX, the `TZ` environment variable typically corresponds
1320 * to the name of a file in the zoneinfo database, or string in
1321 * "std offset [dst [offset],start[/time],end[/time]]" (POSIX) format.
1322 * There are no spaces in the specification. The name of standard
1323 * and daylight savings time zone must be three or more alphabetic
1324 * characters. Offsets are time values to be added to local time to
1325 * get Coordinated Universal Time (UTC) and should be
1326 * <literal>"[±]hh[[:]mm[:ss]]"</literal>. Dates are either
1327 * <literal>"Jn"</literal> (Julian day with n between 1 and 365, leap
1328 * years not counted), <literal>"n"</literal> (zero-based Julian day
1329 * with n between 0 and 365) or <literal>"Mm.w.d"</literal> (day d
1330 * (0 <= d <= 6) of week w (1 <= w <= 5) of month m (1 <= m <= 12), day
1331 * 0 is a Sunday). Times are in local wall clock time, the default is
1334 * In Windows, the "tzn[+|–]hh[:mm[:ss]][dzn]" format is used, but also
1335 * accepts POSIX format. The Windows format uses US rules for all time
1336 * zones; daylight savings time is 60 minutes behind the standard time
1337 * with date and time of change taken from Pacific Standard Time.
1338 * Offsets are time values to be added to the local time to get
1339 * Coordinated Universal Time (UTC).
1341 * g_time_zone_new_local() calls this function with the value of the
1342 * `TZ` environment variable. This function itself is independent of
1343 * the value of `TZ`, but if @identifier is %NULL then `/etc/localtime`
1344 * will be consulted to discover the correct time zone on UNIX and the
1345 * registry will be consulted or GetTimeZoneInformation() will be used
1346 * to get the local time zone on Windows.
1348 * If intervals are not available, only time zone rules from `TZ`
1349 * environment variable or other means, then they will be computed
1350 * from year 1900 to 2037. If the maximum year for the rules is
1351 * available and it is greater than 2037, then it will followed
1355 * [RFC3339 §5.6](http://tools.ietf.org/html/rfc3339#section-5.6)
1356 * for a precise definition of valid RFC3339 time offsets
1357 * (the <literal>time-offset</literal> expansion) and ISO 8601 for the
1358 * full list of valid time offsets. See
1359 * [The GNU C Library manual](http://www.gnu.org/s/libc/manual/html_node/TZ-Variable.html)
1360 * for an explanation of the possible
1361 * values of the `TZ` environment variable. See
1362 * [Microsoft Time Zone Index Values](http://msdn.microsoft.com/en-us/library/ms912391%28v=winembedded.11%29.aspx)
1363 * for the list of time zones on Windows.
1365 * You should release the return value by calling g_time_zone_unref()
1366 * when you are done with it.
1368 * Returns: the requested timezone
1373 g_time_zone_new (const gchar *identifier)
1375 GTimeZone *tz = NULL;
1376 TimeZoneRule *rules;
1379 G_LOCK (time_zones);
1380 if (time_zones == NULL)
1381 time_zones = g_hash_table_new (g_str_hash, g_str_equal);
1385 tz = g_hash_table_lookup (time_zones, identifier);
1388 g_atomic_int_inc (&tz->ref_count);
1389 G_UNLOCK (time_zones);
1394 tz = g_slice_new0 (GTimeZone);
1395 tz->name = g_strdup (identifier);
1398 zone_for_constant_offset (tz, identifier);
1400 if (tz->t_info == NULL &&
1401 (rules_num = rules_from_identifier (identifier, &rules)))
1403 init_zone_from_rules (tz, rules, rules_num);
1407 if (tz->t_info == NULL)
1410 GBytes *zoneinfo = zone_info_unix (identifier);
1412 zone_for_constant_offset (tz, "UTC");
1415 init_zone_from_iana_info (tz, zoneinfo);
1416 g_bytes_unref (zoneinfo);
1418 #elif defined (G_OS_WIN32)
1419 if ((rules_num = rules_from_windows_time_zone (identifier, &rules)))
1421 init_zone_from_rules (tz, rules, rules_num);
1426 if (tz->t_info == NULL)
1429 zone_for_constant_offset (tz, "UTC");
1432 TIME_ZONE_INFORMATION tzi;
1434 if (GetTimeZoneInformation (&tzi) != TIME_ZONE_ID_INVALID)
1436 rules = g_new0 (TimeZoneRule, 2);
1438 rule_from_windows_time_zone_info (&rules[0], &tzi);
1440 memset (rules[0].std_name, 0, NAME_SIZE);
1441 memset (rules[0].dlt_name, 0, NAME_SIZE);
1443 rules[0].start_year = MIN_TZYEAR;
1444 rules[1].start_year = MAX_TZYEAR;
1446 init_zone_from_rules (tz, rules, 2);
1454 if (tz->t_info != NULL)
1457 g_hash_table_insert (time_zones, tz->name, tz);
1459 g_atomic_int_inc (&tz->ref_count);
1460 G_UNLOCK (time_zones);
1466 * g_time_zone_new_utc:
1468 * Creates a #GTimeZone corresponding to UTC.
1470 * This is equivalent to calling g_time_zone_new() with a value like
1471 * "Z", "UTC", "+00", etc.
1473 * You should release the return value by calling g_time_zone_unref()
1474 * when you are done with it.
1476 * Returns: the universal timezone
1481 g_time_zone_new_utc (void)
1483 return g_time_zone_new ("UTC");
1487 * g_time_zone_new_local:
1489 * Creates a #GTimeZone corresponding to local time. The local time
1490 * zone may change between invocations to this function; for example,
1491 * if the system administrator changes it.
1493 * This is equivalent to calling g_time_zone_new() with the value of
1494 * the `TZ` environment variable (including the possibility of %NULL).
1496 * You should release the return value by calling g_time_zone_unref()
1497 * when you are done with it.
1499 * Returns: the local timezone
1504 g_time_zone_new_local (void)
1506 return g_time_zone_new (getenv ("TZ"));
1509 #define TRANSITION(n) g_array_index (tz->transitions, Transition, n)
1510 #define TRANSITION_INFO(n) g_array_index (tz->t_info, TransitionInfo, n)
1512 /* Internal helpers {{{1 */
1513 /* NB: Interval 0 is before the first transition, so there's no
1514 * transition structure to point to which TransitionInfo to
1515 * use. Rule-based zones are set up so that TI 0 is always standard
1516 * time (which is what's in effect before Daylight time got started
1517 * in the early 20th century), but IANA tzfiles don't follow that
1518 * convention. The tzfile documentation says to use the first
1519 * standard-time (i.e., non-DST) tinfo, so that's what we do.
1521 inline static const TransitionInfo*
1522 interval_info (GTimeZone *tz,
1526 g_return_val_if_fail (tz->t_info != NULL, NULL);
1527 if (interval && tz->transitions && interval <= tz->transitions->len)
1528 index = (TRANSITION(interval - 1)).info_index;
1531 for (index = 0; index < tz->t_info->len; index++)
1533 TransitionInfo *tzinfo = &(TRANSITION_INFO(index));
1534 if (!tzinfo->is_dst)
1540 return &(TRANSITION_INFO(index));
1543 inline static gint64
1544 interval_start (GTimeZone *tz,
1547 if (!interval || tz->transitions == NULL || tz->transitions->len == 0)
1549 if (interval > tz->transitions->len)
1550 interval = tz->transitions->len;
1551 return (TRANSITION(interval - 1)).time;
1554 inline static gint64
1555 interval_end (GTimeZone *tz,
1558 if (tz->transitions && interval < tz->transitions->len)
1559 return (TRANSITION(interval)).time - 1;
1563 inline static gint32
1564 interval_offset (GTimeZone *tz,
1567 g_return_val_if_fail (tz->t_info != NULL, 0);
1568 return interval_info (tz, interval)->gmt_offset;
1571 inline static gboolean
1572 interval_isdst (GTimeZone *tz,
1575 g_return_val_if_fail (tz->t_info != NULL, 0);
1576 return interval_info (tz, interval)->is_dst;
1580 inline static gboolean
1581 interval_isgmt (GTimeZone *tz,
1584 g_return_val_if_fail (tz->t_info != NULL, 0);
1585 return interval_info (tz, interval)->is_gmt;
1588 inline static gboolean
1589 interval_isstandard (GTimeZone *tz,
1592 return interval_info (tz, interval)->is_standard;
1595 inline static gchar*
1596 interval_abbrev (GTimeZone *tz,
1599 g_return_val_if_fail (tz->t_info != NULL, 0);
1600 return interval_info (tz, interval)->abbrev;
1603 inline static gint64
1604 interval_local_start (GTimeZone *tz,
1608 return interval_start (tz, interval) + interval_offset (tz, interval);
1613 inline static gint64
1614 interval_local_end (GTimeZone *tz,
1617 if (tz->transitions && interval < tz->transitions->len)
1618 return interval_end (tz, interval) + interval_offset (tz, interval);
1624 interval_valid (GTimeZone *tz,
1627 if ( tz->transitions == NULL)
1628 return interval == 0;
1629 return interval <= tz->transitions->len;
1632 /* g_time_zone_find_interval() {{{1 */
1635 * g_time_zone_adjust_time:
1637 * @type: the #GTimeType of @time_
1638 * @time_: a pointer to a number of seconds since January 1, 1970
1640 * Finds an interval within @tz that corresponds to the given @time_,
1641 * possibly adjusting @time_ if required to fit into an interval.
1642 * The meaning of @time_ depends on @type.
1644 * This function is similar to g_time_zone_find_interval(), with the
1645 * difference that it always succeeds (by making the adjustments
1648 * In any of the cases where g_time_zone_find_interval() succeeds then
1649 * this function returns the same value, without modifying @time_.
1651 * This function may, however, modify @time_ in order to deal with
1652 * non-existent times. If the non-existent local @time_ of 02:30 were
1653 * requested on March 14th 2010 in Toronto then this function would
1654 * adjust @time_ to be 03:00 and return the interval containing the
1657 * Returns: the interval containing @time_, never -1
1662 g_time_zone_adjust_time (GTimeZone *tz,
1669 if (tz->transitions == NULL)
1672 intervals = tz->transitions->len;
1674 /* find the interval containing *time UTC
1675 * TODO: this could be binary searched (or better) */
1676 for (i = 0; i <= intervals; i++)
1677 if (*time_ <= interval_end (tz, i))
1680 g_assert (interval_start (tz, i) <= *time_ && *time_ <= interval_end (tz, i));
1682 if (type != G_TIME_TYPE_UNIVERSAL)
1684 if (*time_ < interval_local_start (tz, i))
1685 /* if time came before the start of this interval... */
1689 /* if it's not in the previous interval... */
1690 if (*time_ > interval_local_end (tz, i))
1692 /* it doesn't exist. fast-forward it. */
1694 *time_ = interval_local_start (tz, i);
1698 else if (*time_ > interval_local_end (tz, i))
1699 /* if time came after the end of this interval... */
1703 /* if it's not in the next interval... */
1704 if (*time_ < interval_local_start (tz, i))
1705 /* it doesn't exist. fast-forward it. */
1706 *time_ = interval_local_start (tz, i);
1709 else if (interval_isdst (tz, i) != type)
1710 /* it's in this interval, but dst flag doesn't match.
1711 * check neighbours for a better fit. */
1713 if (i && *time_ <= interval_local_end (tz, i - 1))
1716 else if (i < intervals &&
1717 *time_ >= interval_local_start (tz, i + 1))
1726 * g_time_zone_find_interval:
1728 * @type: the #GTimeType of @time_
1729 * @time_: a number of seconds since January 1, 1970
1731 * Finds an the interval within @tz that corresponds to the given @time_.
1732 * The meaning of @time_ depends on @type.
1734 * If @type is %G_TIME_TYPE_UNIVERSAL then this function will always
1735 * succeed (since universal time is monotonic and continuous).
1737 * Otherwise @time_ is treated is local time. The distinction between
1738 * %G_TIME_TYPE_STANDARD and %G_TIME_TYPE_DAYLIGHT is ignored except in
1739 * the case that the given @time_ is ambiguous. In Toronto, for example,
1740 * 01:30 on November 7th 2010 occurred twice (once inside of daylight
1741 * savings time and the next, an hour later, outside of daylight savings
1742 * time). In this case, the different value of @type would result in a
1743 * different interval being returned.
1745 * It is still possible for this function to fail. In Toronto, for
1746 * example, 02:00 on March 14th 2010 does not exist (due to the leap
1747 * forward to begin daylight savings time). -1 is returned in that
1750 * Returns: the interval containing @time_, or -1 in case of failure
1755 g_time_zone_find_interval (GTimeZone *tz,
1762 if (tz->transitions == NULL)
1764 intervals = tz->transitions->len;
1765 for (i = 0; i <= intervals; i++)
1766 if (time_ <= interval_end (tz, i))
1769 if (type == G_TIME_TYPE_UNIVERSAL)
1772 if (time_ < interval_local_start (tz, i))
1774 if (time_ > interval_local_end (tz, --i))
1778 else if (time_ > interval_local_end (tz, i))
1780 if (time_ < interval_local_start (tz, ++i))
1784 else if (interval_isdst (tz, i) != type)
1786 if (i && time_ <= interval_local_end (tz, i - 1))
1789 else if (i < intervals && time_ >= interval_local_start (tz, i + 1))
1796 /* Public API accessors {{{1 */
1799 * g_time_zone_get_abbreviation:
1801 * @interval: an interval within the timezone
1803 * Determines the time zone abbreviation to be used during a particular
1804 * @interval of time in the time zone @tz.
1806 * For example, in Toronto this is currently "EST" during the winter
1807 * months and "EDT" during the summer months when daylight savings time
1810 * Returns: the time zone abbreviation, which belongs to @tz
1815 g_time_zone_get_abbreviation (GTimeZone *tz,
1818 g_return_val_if_fail (interval_valid (tz, (guint)interval), NULL);
1820 return interval_abbrev (tz, (guint)interval);
1824 * g_time_zone_get_offset:
1826 * @interval: an interval within the timezone
1828 * Determines the offset to UTC in effect during a particular @interval
1829 * of time in the time zone @tz.
1831 * The offset is the number of seconds that you add to UTC time to
1832 * arrive at local time for @tz (ie: negative numbers for time zones
1833 * west of GMT, positive numbers for east).
1835 * Returns: the number of seconds that should be added to UTC to get the
1841 g_time_zone_get_offset (GTimeZone *tz,
1844 g_return_val_if_fail (interval_valid (tz, (guint)interval), 0);
1846 return interval_offset (tz, (guint)interval);
1850 * g_time_zone_is_dst:
1852 * @interval: an interval within the timezone
1854 * Determines if daylight savings time is in effect during a particular
1855 * @interval of time in the time zone @tz.
1857 * Returns: %TRUE if daylight savings time is in effect
1862 g_time_zone_is_dst (GTimeZone *tz,
1865 g_return_val_if_fail (interval_valid (tz, interval), FALSE);
1867 if (tz->transitions == NULL)
1870 return interval_isdst (tz, (guint)interval);
1874 /* vim:set foldmethod=marker: */