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 * #GDateTime 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)
236 g_array_free (tz->t_info, TRUE);
237 if (tz->transitions != NULL)
238 g_array_free (tz->transitions, TRUE);
241 g_slice_free (GTimeZone, tz);
244 else if G_UNLIKELY (!g_atomic_int_compare_and_exchange (&tz->ref_count,
254 * Increases the reference count on @tz.
256 * Returns: a new reference to @tz.
261 g_time_zone_ref (GTimeZone *tz)
263 g_assert (tz->ref_count > 0);
265 g_atomic_int_inc (&tz->ref_count);
270 /* fake zoneinfo creation (for RFC3339/ISO 8601 timezones) {{{1 */
272 * parses strings of the form h or hh[[:]mm[[[:]ss]]] where:
278 parse_time (const gchar *time_,
281 if (*time_ < '0' || '9' < *time_)
284 *offset = 60 * 60 * (*time_++ - '0');
291 if (*time_ < '0' || '9' < *time_)
295 *offset += 60 * 60 * (*time_++ - '0');
297 if (*offset > 23 * 60 * 60)
307 if (*time_ < '0' || '5' < *time_)
310 *offset += 10 * 60 * (*time_++ - '0');
312 if (*time_ < '0' || '9' < *time_)
315 *offset += 60 * (*time_++ - '0');
323 if (*time_ < '0' || '5' < *time_)
326 *offset += 10 * (*time_++ - '0');
328 if (*time_ < '0' || '9' < *time_)
331 *offset += *time_++ - '0';
333 return *time_ == '\0';
337 parse_constant_offset (const gchar *name,
340 if (g_strcmp0 (name, "UTC") == 0)
346 if (*name >= '0' && '9' >= *name)
347 return parse_time (name, offset);
356 return parse_time (name, offset);
359 if (parse_time (name, offset))
371 zone_for_constant_offset (GTimeZone *gtz, const gchar *name)
376 if (name == NULL || !parse_constant_offset (name, &offset))
379 info.gmt_offset = offset;
381 info.is_standard = TRUE;
383 info.abbrev = g_strdup (name);
386 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), 1);
387 g_array_append_val (gtz->t_info, info);
389 /* Constant offset, no transitions */
390 gtz->transitions = NULL;
395 zone_info_unix (const gchar *identifier)
398 GMappedFile *file = NULL;
399 GBytes *zoneinfo = NULL;
401 /* identifier can be a relative or absolute path name;
402 if relative, it is interpreted starting from /usr/share/zoneinfo
403 while the POSIX standard says it should start with :,
404 glibc allows both syntaxes, so we should too */
405 if (identifier != NULL)
409 tzdir = getenv ("TZDIR");
411 tzdir = "/usr/share/zoneinfo";
413 if (*identifier == ':')
416 if (g_path_is_absolute (identifier))
417 filename = g_strdup (identifier);
419 filename = g_build_filename (tzdir, identifier, NULL);
422 filename = g_strdup ("/etc/localtime");
424 file = g_mapped_file_new (filename, FALSE, NULL);
427 zoneinfo = g_bytes_new_with_free_func (g_mapped_file_get_contents (file),
428 g_mapped_file_get_length (file),
429 (GDestroyNotify)g_mapped_file_unref,
430 g_mapped_file_ref (file));
431 g_mapped_file_unref (file);
438 init_zone_from_iana_info (GTimeZone *gtz, GBytes *zoneinfo)
442 guint32 time_count, type_count, leap_count, isgmt_count;
443 guint32 isstd_count, char_count ;
444 guint8 *tz_transitions, *tz_type_index, *tz_ttinfo;
445 guint8 *tz_leaps, *tz_isgmt, *tz_isstd;
447 gsize timesize = sizeof (gint32), countsize = sizeof (gint32);
448 const struct tzhead *header = g_bytes_get_data (zoneinfo, &size);
450 g_return_if_fail (size >= sizeof (struct tzhead) &&
451 memcmp (header, "TZif", 4) == 0);
453 if (header->tzh_version == '2')
455 /* Skip ahead to the newer 64-bit data if it's available. */
456 header = (const struct tzhead *)
457 (((const gchar *) (header + 1)) +
458 guint32_from_be(header->tzh_ttisgmtcnt) +
459 guint32_from_be(header->tzh_ttisstdcnt) +
460 8 * guint32_from_be(header->tzh_leapcnt) +
461 5 * guint32_from_be(header->tzh_timecnt) +
462 6 * guint32_from_be(header->tzh_typecnt) +
463 guint32_from_be(header->tzh_charcnt));
464 timesize = sizeof (gint64);
466 time_count = guint32_from_be(header->tzh_timecnt);
467 type_count = guint32_from_be(header->tzh_typecnt);
468 leap_count = guint32_from_be(header->tzh_leapcnt);
469 isgmt_count = guint32_from_be(header->tzh_ttisgmtcnt);
470 isstd_count = guint32_from_be(header->tzh_ttisstdcnt);
471 char_count = guint32_from_be(header->tzh_charcnt);
473 g_assert (type_count == isgmt_count);
474 g_assert (type_count == isstd_count);
476 tz_transitions = ((guint8 *) (header) + sizeof (*header));
477 tz_type_index = tz_transitions + timesize * time_count;
478 tz_ttinfo = tz_type_index + time_count;
479 tz_abbrs = tz_ttinfo + sizeof (struct ttinfo) * type_count;
480 tz_leaps = tz_abbrs + char_count;
481 tz_isstd = tz_leaps + (timesize + countsize) * leap_count;
482 tz_isgmt = tz_isstd + isstd_count;
484 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo),
486 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition),
489 for (index = 0; index < type_count; index++)
491 TransitionInfo t_info;
492 struct ttinfo info = ((struct ttinfo*)tz_ttinfo)[index];
493 t_info.gmt_offset = gint32_from_be (info.tt_gmtoff);
494 t_info.is_dst = info.tt_isdst ? TRUE : FALSE;
495 t_info.is_standard = tz_isstd[index] ? TRUE : FALSE;
496 t_info.is_gmt = tz_isgmt[index] ? TRUE : FALSE;
497 t_info.abbrev = g_strdup ((gchar *) &tz_abbrs[info.tt_abbrind]);
498 g_array_append_val (gtz->t_info, t_info);
501 for (index = 0; index < time_count; index++)
504 if (header->tzh_version == '2')
505 trans.time = gint64_from_be (((gint64_be*)tz_transitions)[index]);
507 trans.time = gint32_from_be (((gint32_be*)tz_transitions)[index]);
508 trans.info_index = tz_type_index[index];
509 g_assert (trans.info_index >= 0);
510 g_assert (trans.info_index < gtz->t_info->len);
511 g_array_append_val (gtz->transitions, trans);
513 g_bytes_unref (zoneinfo);
516 #elif defined (G_OS_WIN32)
519 copy_windows_systemtime (SYSTEMTIME *s_time, TimeZoneDate *tzdate)
521 tzdate->sec = s_time->wSecond;
522 tzdate->min = s_time->wMinute;
523 tzdate->hour = s_time->wHour;
524 tzdate->mon = s_time->wMonth;
525 tzdate->year = s_time->wYear;
526 tzdate->wday = s_time->wDayOfWeek ? s_time->wDayOfWeek : 7;
530 tzdate->mday = s_time->wDay;
534 tzdate->week = s_time->wDay;
537 /* UTC = local time + bias while local time = UTC + offset */
539 rule_from_windows_time_zone_info (TimeZoneRule *rule,
540 TIME_ZONE_INFORMATION *tzi)
543 if (tzi->StandardDate.wMonth)
545 rule->std_offset = -(tzi->Bias + tzi->StandardBias) * 60;
546 rule->dlt_offset = -(tzi->Bias + tzi->DaylightBias) * 60;
547 copy_windows_systemtime (&(tzi->DaylightDate), &(rule->dlt_start));
549 copy_windows_systemtime (&(tzi->StandardDate), &(rule->dlt_end));
555 rule->std_offset = -tzi->Bias * 60;
556 rule->dlt_start.mon = 0;
558 strncpy (rule->std_name, (gchar*)tzi->StandardName, NAME_SIZE - 1);
559 strncpy (rule->dlt_name, (gchar*)tzi->DaylightName, NAME_SIZE - 1);
563 windows_default_tzname (void)
565 const gchar *subkey =
566 "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation";
568 gchar *key_name = NULL;
569 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
570 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
573 if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
574 NULL, &size) == ERROR_SUCCESS)
576 key_name = g_malloc ((gint)size);
577 if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
578 (LPBYTE)key_name, &size) != ERROR_SUCCESS)
594 SYSTEMTIME StandardDate;
595 SYSTEMTIME DaylightDate;
599 system_time_copy (SYSTEMTIME *orig, SYSTEMTIME *target)
601 g_return_if_fail (orig != NULL);
602 g_return_if_fail (target != NULL);
604 target->wYear = orig->wYear;
605 target->wMonth = orig->wMonth;
606 target->wDayOfWeek = orig->wDayOfWeek;
607 target->wDay = orig->wDay;
608 target->wHour = orig->wHour;
609 target->wMinute = orig->wMinute;
610 target->wSecond = orig->wSecond;
611 target->wMilliseconds = orig->wMilliseconds;
615 register_tzi_to_tzi (RegTZI *reg, TIME_ZONE_INFORMATION *tzi)
617 g_return_if_fail (reg != NULL);
618 g_return_if_fail (tzi != NULL);
619 tzi->Bias = reg->Bias;
620 system_time_copy (&(reg->StandardDate), &(tzi->StandardDate));
621 tzi->StandardBias = reg->StandardBias;
622 system_time_copy (&(reg->DaylightDate), &(tzi->DaylightDate));
623 tzi->DaylightBias = reg->DaylightBias;
627 rules_from_windows_time_zone (const gchar *identifier, TimeZoneRule **rules)
630 gchar *subkey, *subkey_dynamic;
631 gchar *key_name = NULL;
632 const gchar *reg_key =
633 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\";
634 TIME_ZONE_INFORMATION tzi;
637 RegTZI regtzi, regtzi_prev;
643 key_name = windows_default_tzname ();
645 key_name = g_strdup (identifier);
650 subkey = g_strconcat (reg_key, key_name, NULL);
651 subkey_dynamic = g_strconcat (subkey, "\\Dynamic DST", NULL);
653 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
654 KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
656 size = sizeof tzi.StandardName;
657 if (RegQueryValueExA (key, "Std", NULL, NULL,
658 (LPBYTE)&(tzi.StandardName), &size) != ERROR_SUCCESS)
660 if (RegQueryValueExA (key, "Dlt", NULL, NULL,
661 (LPBYTE)&(tzi.DaylightName), &size) != ERROR_SUCCESS)
665 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey_dynamic, 0,
666 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
673 if (RegQueryValueExA (key, "FirstEntry", NULL, NULL,
674 (LPBYTE) &first, &size) != ERROR_SUCCESS)
678 if (RegQueryValueExA (key, "LastEntry", NULL, NULL,
679 (LPBYTE) &last, &size) != ERROR_SUCCESS)
682 rules_num = last - first + 2;
683 *rules = g_new0 (TimeZoneRule, rules_num);
685 for (year = first, i = 0; year <= last; year++)
687 s = g_strdup_printf ("%d", year);
689 size = sizeof regtzi;
690 if (RegQueryValueExA (key, s, NULL, NULL,
691 (LPBYTE) ®tzi, &size) != ERROR_SUCCESS)
700 if (year > first && memcmp (®tzi_prev, ®tzi, sizeof regtzi) == 0)
703 memcpy (®tzi_prev, ®tzi, sizeof regtzi);
705 register_tzi_to_tzi (®tzi, &tzi);
706 rule_from_windows_time_zone_info (&(*rules)[i], &tzi);
707 (*rules)[i++].start_year = year;
715 else if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
716 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
718 size = sizeof regtzi;
719 if (RegQueryValueExA (key, "TZI", NULL, NULL,
720 (LPBYTE) ®tzi, &size) == ERROR_SUCCESS)
723 *rules = g_new0 (TimeZoneRule, 2);
724 register_tzi_to_tzi (®tzi, &tzi);
725 rule_from_windows_time_zone_info (&(*rules)[0], &tzi);
731 g_free (subkey_dynamic);
737 (*rules)[0].start_year = MIN_TZYEAR;
738 if ((*rules)[rules_num - 2].start_year < MAX_TZYEAR)
739 (*rules)[rules_num - 1].start_year = MAX_TZYEAR;
741 (*rules)[rules_num - 1].start_year = (*rules)[rules_num - 2].start_year + 1;
752 find_relative_date (TimeZoneDate *buffer)
756 g_date_clear (&date, 1);
759 /* Get last day if last is needed, first day otherwise */
760 if (buffer->mon == 13 || buffer->mon == 14) /* Julian Date */
762 g_date_set_dmy (&date, 1, 1, buffer->year);
763 if (wday >= 59 && buffer->mon == 13 && g_date_is_leap_year (buffer->year))
764 g_date_add_days (&date, wday);
766 g_date_add_days (&date, wday - 1);
767 buffer->mon = (int) g_date_get_month (&date);
768 buffer->mday = (int) g_date_get_day (&date);
774 guint days_in_month = g_date_days_in_month (buffer->mon, buffer->year);
775 GDateWeekday first_wday;
777 g_date_set_dmy (&date, 1, buffer->mon, buffer->year);
778 first_wday = g_date_get_weekday (&date);
780 if (first_wday > wday)
782 /* week is 1 <= w <= 5, we need 0-based */
783 days = 7 * (buffer->week - 1) + wday - first_wday;
785 while (days > days_in_month)
788 g_date_add_days (&date, days);
790 buffer->mday = g_date_get_day (&date);
794 /* Offset is previous offset of local time. Returns 0 if month is 0 */
796 boundary_for_year (TimeZoneDate *boundary,
802 const guint64 unix_epoch_start = 719163L;
803 const guint64 seconds_per_day = 86400L;
809 if (boundary->year == 0)
814 find_relative_date (&buffer);
817 g_assert (buffer.year == year);
818 g_date_clear (&date, 1);
819 g_date_set_dmy (&date, buffer.mday, buffer.mon, buffer.year);
820 return ((g_date_get_julian (&date) - unix_epoch_start) * seconds_per_day +
821 buffer.hour * 3600 + buffer.min * 60 + buffer.sec - offset);
825 fill_transition_info_from_rule (TransitionInfo *info,
829 gint offset = is_dst ? rule->dlt_offset : rule->std_offset;
830 gchar *name = is_dst ? rule->dlt_name : rule->std_name;
832 info->gmt_offset = offset;
833 info->is_dst = is_dst;
834 info->is_standard = FALSE;
835 info->is_gmt = FALSE;
838 info->abbrev = g_strdup (name);
841 info->abbrev = g_strdup_printf ("%+03d%02d",
843 (int) abs (offset / 60) % 60);
847 init_zone_from_rules (GTimeZone *gtz,
851 guint type_count = 0, trans_count = 0, info_index = 0;
852 guint ri; /* rule index */
853 gboolean skip_first_std_trans = TRUE;
859 /* Last rule only contains max year */
860 for (ri = 0; ri < rules_num - 1; ri++)
862 if (rules[ri].dlt_start.mon || rules[ri].dlt_end.mon)
864 guint rulespan = (rules[ri + 1].start_year - rules[ri].start_year);
865 guint transitions = rules[ri].dlt_start.mon > 0 ? 1 : 0;
866 transitions += rules[ri].dlt_end.mon > 0 ? 1 : 0;
867 type_count += rules[ri].dlt_start.mon > 0 ? 2 : 1;
868 trans_count += transitions * rulespan;
874 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), type_count);
875 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition), trans_count);
877 last_offset = rules[0].std_offset;
879 for (ri = 0; ri < rules_num - 1; ri++)
881 if ((rules[ri].std_offset || rules[ri].dlt_offset) &&
882 rules[ri].dlt_start.mon == 0 && rules[ri].dlt_end.mon == 0)
884 TransitionInfo std_info;
886 fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
887 g_array_append_val (gtz->t_info, std_info);
890 ((rules[ri - 1].dlt_start.mon > 12 &&
891 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
892 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
894 /* The previous rule was a southern hemisphere rule that
895 starts the year with DST, so we need to add a
896 transition to return to standard time */
897 guint year = rules[ri].start_year;
898 gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
900 Transition std_trans = {std_time, info_index};
901 g_array_append_val (gtz->transitions, std_trans);
904 last_offset = rules[ri].std_offset;
906 skip_first_std_trans = TRUE;
908 else if (rules[ri].std_offset || rules[ri].dlt_offset)
910 const guint start_year = rules[ri].start_year;
911 const guint end_year = rules[ri + 1].start_year;
914 TransitionInfo std_info, dlt_info;
915 if (rules[ri].dlt_start.mon > 12)
916 dlt_first = rules[ri].dlt_start.wday > rules[ri].dlt_end.wday;
918 dlt_first = rules[ri].dlt_start.mon > rules[ri].dlt_end.mon;
919 /* Standard rules are always even, because before the first
920 transition is always standard time, and 0 is even. */
921 fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
922 fill_transition_info_from_rule (&dlt_info, &(rules[ri]), TRUE);
924 g_array_append_val (gtz->t_info, std_info);
925 g_array_append_val (gtz->t_info, dlt_info);
927 /* Transition dates. We hope that a year which ends daylight
928 time in a southern-hemisphere country (i.e., one that
929 begins the year in daylight time) will include a rule
930 which has only a dlt_end. */
931 for (year = start_year; year < end_year; year++)
933 gint32 dlt_offset = (dlt_first ? last_offset :
934 rules[ri].dlt_offset);
935 gint32 std_offset = (dlt_first ? rules[ri].std_offset :
937 /* NB: boundary_for_year returns 0 if mon == 0 */
938 gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
940 gint64 dlt_time = boundary_for_year (&rules[ri].dlt_start,
942 Transition std_trans = {std_time, info_index};
943 Transition dlt_trans = {dlt_time, info_index + 1};
944 last_offset = (dlt_first ? rules[ri].dlt_offset :
945 rules[ri].std_offset);
948 if (skip_first_std_trans)
949 skip_first_std_trans = FALSE;
951 g_array_append_val (gtz->transitions, std_trans);
953 g_array_append_val (gtz->transitions, dlt_trans);
958 g_array_append_val (gtz->transitions, dlt_trans);
960 g_array_append_val (gtz->transitions, std_trans);
968 ((rules[ri - 1].dlt_start.mon > 12 &&
969 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
970 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
972 /* The previous rule was a southern hemisphere rule that
973 starts the year with DST, so we need to add a
974 transition to return to standard time */
976 guint year = rules[ri].start_year;
978 fill_transition_info_from_rule (&info, &(rules[ri - 1]), FALSE);
979 g_array_append_val (gtz->t_info, info);
980 trans.time = boundary_for_year (&rules[ri - 1].dlt_end,
982 trans.info_index = info_index;
983 g_array_append_val (gtz->transitions, trans);
988 * parses date[/time] for parsing TZ environment variable
990 * date is either Mm.w.d, Jn or N
997 * time is either h or hh[[:]mm[[[:]ss]]]
1003 parse_mwd_boundary (gchar **pos, TimeZoneDate *boundary)
1005 gint month, week, day;
1007 if (**pos == '\0' || **pos < '0' || '9' < **pos)
1010 month = *(*pos)++ - '0';
1012 if ((month == 1 && **pos >= '0' && '2' >= **pos) ||
1013 (month == 0 && **pos >= '0' && '9' >= **pos))
1016 month += *(*pos)++ - '0';
1019 if (*(*pos)++ != '.' || month == 0)
1022 if (**pos == '\0' || **pos < '1' || '5' < **pos)
1025 week = *(*pos)++ - '0';
1027 if (*(*pos)++ != '.')
1030 if (**pos == '\0' || **pos < '0' || '6' < **pos)
1033 day = *(*pos)++ - '0';
1039 boundary->mon = month;
1040 boundary->week = week;
1041 boundary->wday = day;
1045 /* Different implementations of tzset interpret the Julian day field
1046 differently. For example, Linux specifies that it should be 1-based
1047 (1 Jan is JD 1) for both Jn and n formats, while zOS and BSD
1048 specify that a Jn JD is 1-based while an n JD is 0-based. Rather
1049 than trying to follow different specs, we will follow GDate's
1050 practice thatIn order to keep it simple, we will follow Linux's
1054 parse_julian_boundary (gchar** pos, TimeZoneDate *boundary,
1055 gboolean ignore_leap)
1060 while (**pos >= '0' && '9' >= **pos)
1063 day += *(*pos)++ - '0';
1066 if (day < 1 || 365 < day)
1069 g_date_clear (&date, 1);
1070 g_date_set_julian (&date, day);
1072 boundary->mon = (int) g_date_get_month (&date);
1073 boundary->mday = (int) g_date_get_day (&date);
1076 if (!ignore_leap && day >= 59)
1083 parse_tz_boundary (const gchar *identifier,
1084 TimeZoneDate *boundary)
1088 pos = (gchar*)identifier;
1089 /* Month-week-weekday */
1093 if (!parse_mwd_boundary (&pos, boundary))
1096 /* Julian date which ignores Feb 29 in leap years */
1097 else if (*pos == 'J')
1100 if (!parse_julian_boundary (&pos, boundary, FALSE))
1103 /* Julian date which counts Feb 29 in leap years */
1104 else if (*pos >= '0' && '9' >= *pos)
1106 if (!parse_julian_boundary (&pos, boundary, TRUE))
1118 if (!parse_time (++pos, &offset))
1121 boundary->hour = offset / 3600;
1122 boundary->min = (offset / 60) % 60;
1123 boundary->sec = offset % 3600;
1134 return *pos == '\0';
1139 create_ruleset_from_rule (TimeZoneRule **rules, TimeZoneRule *rule)
1141 *rules = g_new0 (TimeZoneRule, 2);
1143 (*rules)[0].start_year = MIN_TZYEAR;
1144 (*rules)[1].start_year = MAX_TZYEAR;
1146 (*rules)[0].std_offset = -rule->std_offset;
1147 (*rules)[0].dlt_offset = -rule->dlt_offset;
1148 (*rules)[0].dlt_start = rule->dlt_start;
1149 (*rules)[0].dlt_end = rule->dlt_end;
1150 strcpy ((*rules)[0].std_name, rule->std_name);
1151 strcpy ((*rules)[0].dlt_name, rule->dlt_name);
1156 parse_offset (gchar **pos, gint32 *target)
1159 gchar *target_pos = *pos;
1162 while (**pos == '+' || **pos == '-' || **pos == ':' ||
1163 (**pos >= '0' && '9' >= **pos))
1166 buffer = g_strndup (target_pos, *pos - target_pos);
1167 ret = parse_constant_offset (buffer, target);
1174 parse_identifier_boundary (gchar **pos, TimeZoneDate *target)
1177 gchar *target_pos = *pos;
1180 while (**pos != ',' && **pos != '\0')
1182 buffer = g_strndup (target_pos, *pos - target_pos);
1183 ret = parse_tz_boundary (buffer, target);
1190 set_tz_name (gchar **pos, gchar *buffer, guint size)
1192 gchar *name_pos = *pos;
1195 /* Name is ASCII alpha (Is this necessarily true?) */
1196 while (g_ascii_isalpha (**pos))
1199 /* Name should be three or more alphabetic characters */
1200 if (*pos - name_pos < 3)
1203 memset (buffer, 0, NAME_SIZE);
1204 /* name_pos isn't 0-terminated, so we have to limit the length expressly */
1205 len = *pos - name_pos > size - 1 ? size - 1 : *pos - name_pos;
1206 strncpy (buffer, name_pos, len);
1211 parse_identifier_boundaries (gchar **pos, TimeZoneRule *tzr)
1213 if (*(*pos)++ != ',')
1217 if (!parse_identifier_boundary (pos, &(tzr->dlt_start)) || *(*pos)++ != ',')
1221 if (!parse_identifier_boundary (pos, &(tzr->dlt_end)))
1227 * Creates an array of TimeZoneRule from a TZ environment variable
1228 * type of identifier. Should free rules afterwards
1231 rules_from_identifier (const gchar *identifier,
1232 TimeZoneRule **rules)
1240 pos = (gchar*)identifier;
1241 memset (&tzr, 0, sizeof (tzr));
1242 /* Standard offset */
1243 if (!(set_tz_name (&pos, tzr.std_name, NAME_SIZE)) ||
1244 !parse_offset (&pos, &(tzr.std_offset)))
1248 return create_ruleset_from_rule (rules, &tzr);
1251 if (!(set_tz_name (&pos, tzr.dlt_name, NAME_SIZE)))
1253 parse_offset (&pos, &(tzr.dlt_offset));
1254 if (tzr.dlt_offset == 0) /* No daylight offset given, assume it's 1
1255 hour earlier that standard */
1256 tzr.dlt_offset = tzr.std_offset - 3600;
1259 /* Windows allows us to use the US DST boundaries if they're not given */
1262 guint rules_num = 0;
1264 /* Use US rules, Windows' default is Pacific Standard Time */
1265 if ((rules_num = rules_from_windows_time_zone ("Pacific Standard Time",
1268 for (i = 0; i < rules_num - 1; i++)
1270 (*rules)[i].std_offset = - tzr.std_offset;
1271 (*rules)[i].dlt_offset = - tzr.dlt_offset;
1272 strcpy ((*rules)[i].std_name, tzr.std_name);
1273 strcpy ((*rules)[i].dlt_name, tzr.dlt_name);
1284 /* Start and end required (format 2) */
1285 if (!parse_identifier_boundaries (&pos, &tzr))
1288 return create_ruleset_from_rule (rules, &tzr);
1291 /* Construction {{{1 */
1294 * @identifier: (allow-none): a timezone identifier
1296 * Creates a #GTimeZone corresponding to @identifier.
1298 * @identifier can either be an RFC3339/ISO 8601 time offset or
1299 * something that would pass as a valid value for the
1300 * <varname>TZ</varname> environment variable (including %NULL).
1302 * In Windows, @identifier can also be the unlocalized name of a time
1303 * zone for standard time, for example "Pacific Standard Time".
1305 * Valid RFC3339 time offsets are <literal>"Z"</literal> (for UTC) or
1306 * <literal>"±hh:mm"</literal>. ISO 8601 additionally specifies
1307 * <literal>"±hhmm"</literal> and <literal>"±hh"</literal>. Offsets are
1308 * time values to be added to Coordinated Universal Time (UTC) to get
1311 * In Unix, the <varname>TZ</varname> environment variable typically
1312 * corresponds to the name of a file in the zoneinfo database, or
1313 * string in "std offset [dst [offset],start[/time],end[/time]]"
1314 * (POSIX) format. There are no spaces in the specification. The
1315 * name of standard and daylight savings time zone must be three or more
1316 * alphabetic characters. Offsets are time values to be added to local
1317 * time to get Coordinated Universal Time (UTC) and should be
1318 * <literal>"[±]hh[[:]mm[:ss]]"</literal>. Dates are either
1319 * <literal>"Jn"</literal> (Julian day with n between 1 and 365, leap
1320 * years not counted), <literal>"n"</literal> (zero-based Julian day
1321 * with n between 0 and 365) or <literal>"Mm.w.d"</literal> (day d
1322 * (0 <= d <= 6) of week w (1 <= w <= 5) of month m (1 <= m <= 12), day
1323 * 0 is a Sunday). Times are in local wall clock time, the default is
1326 * In Windows, the "tzn[+|–]hh[:mm[:ss]][dzn]" format is used, but also
1327 * accepts POSIX format. The Windows format uses US rules for all time
1328 * zones; daylight savings time is 60 minutes behind the standard time
1329 * with date and time of change taken from Pacific Standard Time.
1330 * Offsets are time values to be added to the local time to get
1331 * Coordinated Universal Time (UTC).
1333 * g_time_zone_new_local() calls this function with the value of the
1334 * <varname>TZ</varname> environment variable. This function itself is
1335 * independent of the value of <varname>TZ</varname>, but if @identifier
1336 * is %NULL then <filename>/etc/localtime</filename> will be consulted
1337 * to discover the correct time zone on Unix and the registry will be
1338 * consulted or GetTimeZoneInformation() will be used to get the local
1339 * time zone on Windows.
1341 * If intervals are not available, only time zone rules from
1342 * <varname>TZ</varname> environment variable or other means, then they
1343 * will be computed from year 1900 to 2037. If the maximum year for the
1344 * rules is available and it is greater than 2037, then it will followed
1348 * url='http://tools.ietf.org/html/rfc3339#section-5.6'>RFC3339
1349 * §5.6</ulink> for a precise definition of valid RFC3339 time offsets
1350 * (the <varname>time-offset</varname> expansion) and ISO 8601 for the
1351 * full list of valid time offsets. See <ulink
1352 * url='http://www.gnu.org/s/libc/manual/html_node/TZ-Variable.html'>The
1353 * GNU C Library manual</ulink> for an explanation of the possible
1354 * values of the <varname>TZ</varname> environment variable. See <ulink
1355 * url='http://msdn.microsoft.com/en-us/library/ms912391%28v=winembedded.11%29.aspx'>
1356 * Microsoft Time Zone Index Values</ulink> for the list of time zones
1359 * You should release the return value by calling g_time_zone_unref()
1360 * when you are done with it.
1362 * Returns: the requested timezone
1367 g_time_zone_new (const gchar *identifier)
1369 GTimeZone *tz = NULL;
1370 TimeZoneRule *rules;
1373 G_LOCK (time_zones);
1374 if (time_zones == NULL)
1375 time_zones = g_hash_table_new (g_str_hash, g_str_equal);
1379 tz = g_hash_table_lookup (time_zones, identifier);
1382 g_atomic_int_inc (&tz->ref_count);
1383 G_UNLOCK (time_zones);
1388 tz = g_slice_new0 (GTimeZone);
1389 tz->name = g_strdup (identifier);
1392 zone_for_constant_offset (tz, identifier);
1394 if (tz->t_info == NULL &&
1395 (rules_num = rules_from_identifier (identifier, &rules)))
1397 init_zone_from_rules (tz, rules, rules_num);
1401 if (tz->t_info == NULL)
1404 GBytes *zoneinfo = zone_info_unix (identifier);
1406 zone_for_constant_offset (tz, "UTC");
1409 init_zone_from_iana_info (tz, zoneinfo);
1410 g_bytes_unref (zoneinfo);
1412 #elif defined (G_OS_WIN32)
1413 if ((rules_num = rules_from_windows_time_zone (identifier, &rules)))
1415 init_zone_from_rules (tz, rules, rules_num);
1420 if (tz->t_info == NULL)
1423 zone_for_constant_offset (tz, "UTC");
1426 TIME_ZONE_INFORMATION tzi;
1428 if (GetTimeZoneInformation (&tzi) != TIME_ZONE_ID_INVALID)
1430 rules = g_new0 (TimeZoneRule, 2);
1432 rule_from_windows_time_zone_info (&rules[0], &tzi);
1434 memset (rules[0].std_name, 0, NAME_SIZE);
1435 memset (rules[0].dlt_name, 0, NAME_SIZE);
1437 rules[0].start_year = MIN_TZYEAR;
1438 rules[1].start_year = MAX_TZYEAR;
1440 init_zone_from_rules (tz, rules, 2);
1448 if (tz->t_info != NULL)
1451 g_hash_table_insert (time_zones, tz->name, tz);
1453 g_atomic_int_inc (&tz->ref_count);
1454 G_UNLOCK (time_zones);
1460 * g_time_zone_new_utc:
1462 * Creates a #GTimeZone corresponding to UTC.
1464 * This is equivalent to calling g_time_zone_new() with a value like
1465 * "Z", "UTC", "+00", etc.
1467 * You should release the return value by calling g_time_zone_unref()
1468 * when you are done with it.
1470 * Returns: the universal timezone
1475 g_time_zone_new_utc (void)
1477 return g_time_zone_new ("UTC");
1481 * g_time_zone_new_local:
1483 * Creates a #GTimeZone corresponding to local time. The local time
1484 * zone may change between invocations to this function; for example,
1485 * if the system administrator changes it.
1487 * This is equivalent to calling g_time_zone_new() with the value of the
1488 * <varname>TZ</varname> environment variable (including the possibility
1491 * You should release the return value by calling g_time_zone_unref()
1492 * when you are done with it.
1494 * Returns: the local timezone
1499 g_time_zone_new_local (void)
1501 return g_time_zone_new (getenv ("TZ"));
1504 #define TRANSITION(n) g_array_index (tz->transitions, Transition, n)
1505 #define TRANSITION_INFO(n) g_array_index (tz->t_info, TransitionInfo, n)
1507 /* Internal helpers {{{1 */
1508 /* NB: Interval 0 is before the first transition, so there's no
1509 * transition structure to point to which TransitionInfo to
1510 * use. Rule-based zones are set up so that TI 0 is always standard
1511 * time (which is what's in effect before Daylight time got started
1512 * in the early 20th century), but IANA tzfiles don't follow that
1513 * convention. The tzfile documentation says to use the first
1514 * standard-time (i.e., non-DST) tinfo, so that's what we do.
1516 inline static const TransitionInfo*
1517 interval_info (GTimeZone *tz,
1521 g_return_val_if_fail (tz->t_info != NULL, NULL);
1522 if (interval && tz->transitions && interval <= tz->transitions->len)
1523 index = (TRANSITION(interval - 1)).info_index;
1526 for (index = 0; index < tz->t_info->len; index++)
1528 TransitionInfo *tzinfo = &(TRANSITION_INFO(index));
1529 if (!tzinfo->is_dst)
1535 return &(TRANSITION_INFO(index));
1538 inline static gint64
1539 interval_start (GTimeZone *tz,
1542 if (!interval || tz->transitions == NULL || tz->transitions->len == 0)
1544 if (interval > tz->transitions->len)
1545 interval = tz->transitions->len;
1546 return (TRANSITION(interval - 1)).time;
1549 inline static gint64
1550 interval_end (GTimeZone *tz,
1553 if (tz->transitions && interval < tz->transitions->len)
1554 return (TRANSITION(interval)).time - 1;
1558 inline static gint32
1559 interval_offset (GTimeZone *tz,
1562 g_return_val_if_fail (tz->t_info != NULL, 0);
1563 return interval_info (tz, interval)->gmt_offset;
1566 inline static gboolean
1567 interval_isdst (GTimeZone *tz,
1570 g_return_val_if_fail (tz->t_info != NULL, 0);
1571 return interval_info (tz, interval)->is_dst;
1575 inline static gboolean
1576 interval_isgmt (GTimeZone *tz,
1579 g_return_val_if_fail (tz->t_info != NULL, 0);
1580 return interval_info (tz, interval)->is_gmt;
1583 inline static gboolean
1584 interval_isstandard (GTimeZone *tz,
1587 return interval_info (tz, interval)->is_standard;
1590 inline static gchar*
1591 interval_abbrev (GTimeZone *tz,
1594 g_return_val_if_fail (tz->t_info != NULL, 0);
1595 return interval_info (tz, interval)->abbrev;
1598 inline static gint64
1599 interval_local_start (GTimeZone *tz,
1603 return interval_start (tz, interval) + interval_offset (tz, interval);
1608 inline static gint64
1609 interval_local_end (GTimeZone *tz,
1612 if (tz->transitions && interval < tz->transitions->len)
1613 return interval_end (tz, interval) + interval_offset (tz, interval);
1619 interval_valid (GTimeZone *tz,
1622 if ( tz->transitions == NULL)
1623 return interval == 0;
1624 return interval <= tz->transitions->len;
1627 /* g_time_zone_find_interval() {{{1 */
1630 * g_time_zone_adjust_time:
1632 * @type: the #GTimeType of @time_
1633 * @time_: a pointer to a number of seconds since January 1, 1970
1635 * Finds an interval within @tz that corresponds to the given @time_,
1636 * possibly adjusting @time_ if required to fit into an interval.
1637 * The meaning of @time_ depends on @type.
1639 * This function is similar to g_time_zone_find_interval(), with the
1640 * difference that it always succeeds (by making the adjustments
1643 * In any of the cases where g_time_zone_find_interval() succeeds then
1644 * this function returns the same value, without modifying @time_.
1646 * This function may, however, modify @time_ in order to deal with
1647 * non-existent times. If the non-existent local @time_ of 02:30 were
1648 * requested on March 14th 2010 in Toronto then this function would
1649 * adjust @time_ to be 03:00 and return the interval containing the
1652 * Returns: the interval containing @time_, never -1
1657 g_time_zone_adjust_time (GTimeZone *tz,
1664 if (tz->transitions == NULL)
1667 intervals = tz->transitions->len;
1669 /* find the interval containing *time UTC
1670 * TODO: this could be binary searched (or better) */
1671 for (i = 0; i <= intervals; i++)
1672 if (*time_ <= interval_end (tz, i))
1675 g_assert (interval_start (tz, i) <= *time_ && *time_ <= interval_end (tz, i));
1677 if (type != G_TIME_TYPE_UNIVERSAL)
1679 if (*time_ < interval_local_start (tz, i))
1680 /* if time came before the start of this interval... */
1684 /* if it's not in the previous interval... */
1685 if (*time_ > interval_local_end (tz, i))
1687 /* it doesn't exist. fast-forward it. */
1689 *time_ = interval_local_start (tz, i);
1693 else if (*time_ > interval_local_end (tz, i))
1694 /* if time came after the end of this interval... */
1698 /* if it's not in the next interval... */
1699 if (*time_ < interval_local_start (tz, i))
1700 /* it doesn't exist. fast-forward it. */
1701 *time_ = interval_local_start (tz, i);
1704 else if (interval_isdst (tz, i) != type)
1705 /* it's in this interval, but dst flag doesn't match.
1706 * check neighbours for a better fit. */
1708 if (i && *time_ <= interval_local_end (tz, i - 1))
1711 else if (i < intervals &&
1712 *time_ >= interval_local_start (tz, i + 1))
1721 * g_time_zone_find_interval:
1723 * @type: the #GTimeType of @time_
1724 * @time_: a number of seconds since January 1, 1970
1726 * Finds an the interval within @tz that corresponds to the given @time_.
1727 * The meaning of @time_ depends on @type.
1729 * If @type is %G_TIME_TYPE_UNIVERSAL then this function will always
1730 * succeed (since universal time is monotonic and continuous).
1732 * Otherwise @time_ is treated is local time. The distinction between
1733 * %G_TIME_TYPE_STANDARD and %G_TIME_TYPE_DAYLIGHT is ignored except in
1734 * the case that the given @time_ is ambiguous. In Toronto, for example,
1735 * 01:30 on November 7th 2010 occurred twice (once inside of daylight
1736 * savings time and the next, an hour later, outside of daylight savings
1737 * time). In this case, the different value of @type would result in a
1738 * different interval being returned.
1740 * It is still possible for this function to fail. In Toronto, for
1741 * example, 02:00 on March 14th 2010 does not exist (due to the leap
1742 * forward to begin daylight savings time). -1 is returned in that
1745 * Returns: the interval containing @time_, or -1 in case of failure
1750 g_time_zone_find_interval (GTimeZone *tz,
1757 if (tz->transitions == NULL)
1759 intervals = tz->transitions->len;
1760 for (i = 0; i <= intervals; i++)
1761 if (time_ <= interval_end (tz, i))
1764 if (type == G_TIME_TYPE_UNIVERSAL)
1767 if (time_ < interval_local_start (tz, i))
1769 if (time_ > interval_local_end (tz, --i))
1773 else if (time_ > interval_local_end (tz, i))
1775 if (time_ < interval_local_start (tz, ++i))
1779 else if (interval_isdst (tz, i) != type)
1781 if (i && time_ <= interval_local_end (tz, i - 1))
1784 else if (i < intervals && time_ >= interval_local_start (tz, i + 1))
1791 /* Public API accessors {{{1 */
1794 * g_time_zone_get_abbreviation:
1796 * @interval: an interval within the timezone
1798 * Determines the time zone abbreviation to be used during a particular
1799 * @interval of time in the time zone @tz.
1801 * For example, in Toronto this is currently "EST" during the winter
1802 * months and "EDT" during the summer months when daylight savings time
1805 * Returns: the time zone abbreviation, which belongs to @tz
1810 g_time_zone_get_abbreviation (GTimeZone *tz,
1813 g_return_val_if_fail (interval_valid (tz, (guint)interval), NULL);
1815 return interval_abbrev (tz, (guint)interval);
1819 * g_time_zone_get_offset:
1821 * @interval: an interval within the timezone
1823 * Determines the offset to UTC in effect during a particular @interval
1824 * of time in the time zone @tz.
1826 * The offset is the number of seconds that you add to UTC time to
1827 * arrive at local time for @tz (ie: negative numbers for time zones
1828 * west of GMT, positive numbers for east).
1830 * Returns: the number of seconds that should be added to UTC to get the
1836 g_time_zone_get_offset (GTimeZone *tz,
1839 g_return_val_if_fail (interval_valid (tz, (guint)interval), 0);
1841 return interval_offset (tz, (guint)interval);
1845 * g_time_zone_is_dst:
1847 * @interval: an interval within the timezone
1849 * Determines if daylight savings time is in effect during a particular
1850 * @interval of time in the time zone @tz.
1852 * Returns: %TRUE if daylight savings time is in effect
1857 g_time_zone_is_dst (GTimeZone *tz,
1860 g_return_val_if_fail (interval_valid (tz, interval), FALSE);
1862 if (tz->transitions == NULL)
1865 return interval_isdst (tz, (guint)interval);
1869 /* vim:set foldmethod=marker: */