2 * Copyright © 2010 Codethink Limited
4 * SPDX-License-Identifier: LGPL-2.1-or-later
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
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"
58 * @short_description: a structure representing a time zone
59 * @see_also: #GDateTime
61 * #GTimeZone is a structure that represents a time zone, at no
62 * particular point in time. It is refcounted and immutable.
64 * Each time zone has an identifier (for example, ‘Europe/London’) which is
65 * platform dependent. See g_time_zone_new() for information on the identifier
66 * formats. The identifier of a time zone can be retrieved using
67 * g_time_zone_get_identifier().
69 * A time zone contains a number of intervals. Each interval has
70 * an abbreviation to describe it (for example, ‘PDT’), an offset to UTC and a
71 * flag indicating if the daylight savings time is in effect during that
72 * interval. A time zone always has at least one interval — interval 0. Note
73 * that interval abbreviations are not the same as time zone identifiers
74 * (apart from ‘UTC’), and cannot be passed to g_time_zone_new().
76 * Every UTC time is contained within exactly one interval, but a given
77 * local time may be contained within zero, one or two intervals (due to
78 * incontinuities associated with daylight savings time).
80 * An interval may refer to a specific period of time (eg: the duration
81 * of daylight savings time during 2010) or it may refer to many periods
82 * of time that share the same properties (eg: all periods of daylight
83 * savings time). It is also possible (usually for political reasons)
84 * that some properties (like the abbreviation) change between intervals
85 * without other properties changing.
87 * #GTimeZone is available since GLib 2.26.
93 * #GTimeZone is an opaque structure whose members cannot be accessed
99 /* IANA zoneinfo file format {{{1 */
102 typedef struct { gchar bytes[8]; } gint64_be;
103 typedef struct { gchar bytes[4]; } gint32_be;
104 typedef struct { gchar bytes[4]; } guint32_be;
106 static inline gint64 gint64_from_be (const gint64_be be) {
107 gint64 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT64_FROM_BE (tmp);
110 static inline gint32 gint32_from_be (const gint32_be be) {
111 gint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT32_FROM_BE (tmp);
114 static inline guint32 guint32_from_be (const guint32_be be) {
115 guint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GUINT32_FROM_BE (tmp);
118 /* The layout of an IANA timezone file header */
123 guchar tzh_reserved[15];
125 guint32_be tzh_ttisgmtcnt;
126 guint32_be tzh_ttisstdcnt;
127 guint32_be tzh_leapcnt;
128 guint32_be tzh_timecnt;
129 guint32_be tzh_typecnt;
130 guint32_be tzh_charcnt;
140 /* A Transition Date structure for TZ Rules, an intermediate structure
141 for parsing MSWindows and Environment-variable time zones. It
142 Generalizes MSWindows's SYSTEMTIME struct.
151 gint32 offset; /* hour*3600 + min*60 + sec; can be negative. */
154 /* POSIX Timezone abbreviations are typically 3 or 4 characters, but
155 Microsoft uses 32-character names. We'll use one larger to ensure
156 we have room for the terminating \0.
160 /* A MSWindows-style time zone transition rule. Generalizes the
161 MSWindows TIME_ZONE_INFORMATION struct. Also used to compose time
162 zones from tzset-style identifiers.
169 TimeZoneDate dlt_start;
170 TimeZoneDate dlt_end;
171 gchar std_name[NAME_SIZE];
172 gchar dlt_name[NAME_SIZE];
175 /* GTimeZone's internal representation of a Daylight Savings (Summer)
185 /* GTimeZone's representation of a transition time to or from Daylight
186 Savings (Summer) time and Standard time for the zone. */
193 /* GTimeZone structure */
197 GArray *t_info; /* Array of TransitionInfo */
198 GArray *transitions; /* Array of Transition */
202 G_LOCK_DEFINE_STATIC (time_zones);
203 static GHashTable/*<string?, GTimeZone>*/ *time_zones;
204 G_LOCK_DEFINE_STATIC (tz_default);
205 static GTimeZone *tz_default = NULL;
206 G_LOCK_DEFINE_STATIC (tz_local);
207 static GTimeZone *tz_local = NULL;
209 #define MIN_TZYEAR 1916 /* Daylight Savings started in WWI */
210 #define MAX_TZYEAR 2999 /* And it's not likely ever to go away, but
211 there's no point in getting carried
215 static GTimeZone *parse_footertz (const gchar *, size_t);
222 * Decreases the reference count on @tz.
227 g_time_zone_unref (GTimeZone *tz)
232 ref_count = g_atomic_int_get (&tz->ref_count);
234 g_assert (ref_count > 0);
238 if (tz->name != NULL)
242 /* someone else might have grabbed a ref in the meantime */
243 if G_UNLIKELY (g_atomic_int_get (&tz->ref_count) != 1)
245 G_UNLOCK(time_zones);
249 if (time_zones != NULL)
250 g_hash_table_remove (time_zones, tz->name);
251 G_UNLOCK(time_zones);
254 if (tz->t_info != NULL)
257 for (idx = 0; idx < tz->t_info->len; idx++)
259 TransitionInfo *info = &g_array_index (tz->t_info, TransitionInfo, idx);
260 g_free (info->abbrev);
262 g_array_free (tz->t_info, TRUE);
264 if (tz->transitions != NULL)
265 g_array_free (tz->transitions, TRUE);
268 g_slice_free (GTimeZone, tz);
271 else if G_UNLIKELY (!g_atomic_int_compare_and_exchange (&tz->ref_count,
281 * Increases the reference count on @tz.
283 * Returns: a new reference to @tz.
288 g_time_zone_ref (GTimeZone *tz)
290 g_assert (tz->ref_count > 0);
292 g_atomic_int_inc (&tz->ref_count);
297 /* fake zoneinfo creation (for RFC3339/ISO 8601 timezones) {{{1 */
299 * parses strings of the form h or hh[[:]mm[[[:]ss]]] where:
303 * If RFC8536, TIME_ is a transition time sans sign,
304 * so colons are required before mm and ss, and hh can be up to 167.
305 * See Internet RFC 8536 section 3.3.1:
306 * https://tools.ietf.org/html/rfc8536#section-3.3.1
307 * and POSIX Base Definitions 8.3 TZ rule time:
308 * https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03
311 parse_time (const gchar *time_,
315 if (*time_ < '0' || '9' < *time_)
318 *offset = 60 * 60 * (*time_++ - '0');
325 if (*time_ < '0' || '9' < *time_)
329 *offset += 60 * 60 * (*time_++ - '0');
333 /* Internet RFC 8536 section 3.3.1 and POSIX 8.3 TZ together say
334 that a transition time must be of the form [+-]hh[:mm[:ss]] where
335 the hours part can range from -167 to 167. */
336 if ('0' <= *time_ && *time_ <= '9')
339 *offset += 60 * 60 * (*time_++ - '0');
341 if (*offset > 167 * 60 * 60)
344 else if (*offset > 24 * 60 * 60)
356 if (*time_ < '0' || '5' < *time_)
359 *offset += 10 * 60 * (*time_++ - '0');
361 if (*time_ < '0' || '9' < *time_)
364 *offset += 60 * (*time_++ - '0');
374 if (*time_ < '0' || '5' < *time_)
377 *offset += 10 * (*time_++ - '0');
379 if (*time_ < '0' || '9' < *time_)
382 *offset += *time_++ - '0';
384 return *time_ == '\0';
388 parse_constant_offset (const gchar *name,
392 /* Internet RFC 8536 section 3.3.1 and POSIX 8.3 TZ together say
393 that a transition time must be numeric. */
394 if (!rfc8536 && g_strcmp0 (name, "UTC") == 0)
400 if (*name >= '0' && '9' >= *name)
401 return parse_time (name, offset, rfc8536);
407 /* Internet RFC 8536 section 3.3.1 requires a numeric zone. */
408 return !rfc8536 && !*name;
411 return parse_time (name, offset, rfc8536);
414 if (parse_time (name, offset, rfc8536))
428 zone_for_constant_offset (GTimeZone *gtz, const gchar *name)
433 if (name == NULL || !parse_constant_offset (name, &offset, FALSE))
436 info.gmt_offset = offset;
438 info.abbrev = g_strdup (name);
440 gtz->name = g_strdup (name);
441 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), 1);
442 g_array_append_val (gtz->t_info, info);
444 /* Constant offset, no transitions */
445 gtz->transitions = NULL;
450 #if defined(__sun) && defined(__SVR4)
452 * only used by Illumos distros or Solaris < 11: parse the /etc/default/init
453 * text file looking for TZ= followed by the timezone, possibly quoted
457 zone_identifier_illumos (void)
459 gchar *resolved_identifier = NULL;
460 gchar *contents = NULL;
461 const gchar *line_start = NULL;
464 if (!g_file_get_contents ("/etc/default/init", &contents, NULL, NULL) )
467 /* is TZ= the first/only line in the file? */
468 if (strncmp (contents, "TZ=", 3) == 0)
470 /* found TZ= on the first line, skip over the TZ= */
471 line_start = contents + 3;
475 /* find a newline followed by TZ= */
476 line_start = strstr (contents, "\nTZ=");
477 if (line_start != NULL)
478 line_start = line_start + 4; /* skip past the \nTZ= */
482 * line_start is NULL if we didn't find TZ= at the start of any line,
483 * otherwise it points to what is after the '=' (possibly '\0')
485 if (line_start == NULL || *line_start == '\0')
488 /* skip past a possible opening " or ' */
489 if (*line_start == '"' || *line_start == '\'')
493 * loop over the next few characters, building up the length of
494 * the timezone identifier, ending with end of string, newline or
497 while (*(line_start + tz_len) != '\0' &&
498 *(line_start + tz_len) != '\n' &&
499 *(line_start + tz_len) != '"' &&
500 *(line_start + tz_len) != '\'')
506 resolved_identifier = g_strndup (line_start, tz_len);
507 g_strchomp (resolved_identifier);
509 return g_steal_pointer (&resolved_identifier);
514 #endif /* defined(__sun) && defined(__SRVR) */
517 * returns the path to the top of the Olson zoneinfo timezone hierarchy.
520 zone_info_base_dir (void)
522 if (g_file_test ("/usr/share/zoneinfo", G_FILE_TEST_IS_DIR))
523 return "/usr/share/zoneinfo"; /* Most distros */
524 else if (g_file_test ("/usr/share/lib/zoneinfo", G_FILE_TEST_IS_DIR))
525 return "/usr/share/lib/zoneinfo"; /* Illumos distros */
527 /* need a better fallback case */
528 return "/usr/share/zoneinfo";
532 zone_identifier_unix (void)
534 gchar *resolved_identifier = NULL;
535 gsize prefix_len = 0;
536 gchar *canonical_path = NULL;
537 GError *read_link_err = NULL;
539 gboolean not_a_symlink_to_zoneinfo = FALSE;
540 struct stat file_status;
542 /* Resolve the actual timezone pointed to by /etc/localtime. */
543 resolved_identifier = g_file_read_link ("/etc/localtime", &read_link_err);
545 if (resolved_identifier != NULL)
547 if (!g_path_is_absolute (resolved_identifier))
549 gchar *absolute_resolved_identifier = g_build_filename ("/etc", resolved_identifier, NULL);
550 g_free (resolved_identifier);
551 resolved_identifier = g_steal_pointer (&absolute_resolved_identifier);
554 if (g_lstat (resolved_identifier, &file_status) == 0)
556 if ((file_status.st_mode & S_IFMT) != S_IFREG)
558 /* Some systems (e.g. toolbox containers) make /etc/localtime be a symlink
561 * Rather than try to cope with that, just ignore /etc/localtime and use
562 * the fallback code to read timezone from /etc/timezone
564 g_clear_pointer (&resolved_identifier, g_free);
565 not_a_symlink_to_zoneinfo = TRUE;
570 g_clear_pointer (&resolved_identifier, g_free);
575 not_a_symlink_to_zoneinfo = g_error_matches (read_link_err,
578 g_clear_error (&read_link_err);
581 if (resolved_identifier == NULL)
583 /* if /etc/localtime is not a symlink, try:
584 * - /var/db/zoneinfo : 'tzsetup' program on FreeBSD and
585 * DragonflyBSD stores the timezone chosen by the user there.
586 * - /etc/timezone : Gentoo, OpenRC, and others store
587 * the user choice there.
588 * - call zone_identifier_illumos iff __sun and __SVR4 are defined,
589 * as a last-ditch effort to parse the TZ= setting from within
592 if (not_a_symlink_to_zoneinfo && (g_file_get_contents ("/var/db/zoneinfo",
593 &resolved_identifier,
595 g_file_get_contents ("/etc/timezone",
596 &resolved_identifier,
598 #if defined(__sun) && defined(__SVR4)
600 (resolved_identifier = zone_identifier_illumos ())
603 g_strchomp (resolved_identifier);
607 g_assert (resolved_identifier == NULL);
613 /* Resolve relative path */
614 canonical_path = g_canonicalize_filename (resolved_identifier, "/etc");
615 g_free (resolved_identifier);
616 resolved_identifier = g_steal_pointer (&canonical_path);
619 tzdir = g_getenv ("TZDIR");
621 tzdir = zone_info_base_dir ();
623 /* Strip the prefix and slashes if possible. */
624 if (g_str_has_prefix (resolved_identifier, tzdir))
626 prefix_len = strlen (tzdir);
627 while (*(resolved_identifier + prefix_len) == '/')
632 memmove (resolved_identifier, resolved_identifier + prefix_len,
633 strlen (resolved_identifier) - prefix_len + 1 /* nul terminator */);
635 g_assert (resolved_identifier != NULL);
638 g_free (canonical_path);
640 return resolved_identifier;
644 zone_info_unix (const gchar *identifier,
645 const gchar *resolved_identifier)
647 gchar *filename = NULL;
648 GMappedFile *file = NULL;
649 GBytes *zoneinfo = NULL;
652 tzdir = g_getenv ("TZDIR");
654 tzdir = zone_info_base_dir ();
656 /* identifier can be a relative or absolute path name;
657 if relative, it is interpreted starting from /usr/share/zoneinfo
658 while the POSIX standard says it should start with :,
659 glibc allows both syntaxes, so we should too */
660 if (identifier != NULL)
662 if (*identifier == ':')
665 if (g_path_is_absolute (identifier))
666 filename = g_strdup (identifier);
668 filename = g_build_filename (tzdir, identifier, NULL);
672 if (resolved_identifier == NULL)
675 filename = g_strdup ("/etc/localtime");
678 file = g_mapped_file_new (filename, FALSE, NULL);
681 zoneinfo = g_bytes_new_with_free_func (g_mapped_file_get_contents (file),
682 g_mapped_file_get_length (file),
683 (GDestroyNotify)g_mapped_file_unref,
684 g_mapped_file_ref (file));
685 g_mapped_file_unref (file);
688 g_assert (resolved_identifier != NULL);
697 init_zone_from_iana_info (GTimeZone *gtz,
699 gchar *identifier /* (transfer full) */)
703 guint32 time_count, type_count;
704 guint8 *tz_transitions, *tz_type_index, *tz_ttinfo;
706 gsize timesize = sizeof (gint32);
707 gconstpointer header_data = g_bytes_get_data (zoneinfo, &size);
708 const gchar *data = header_data;
709 const struct tzhead *header = header_data;
710 GTimeZone *footertz = NULL;
711 guint extra_time_count = 0, extra_type_count = 0;
712 gint64 last_explicit_transition_time;
714 g_return_if_fail (size >= sizeof (struct tzhead) &&
715 memcmp (header, "TZif", 4) == 0);
717 /* FIXME: Handle invalid TZif files better (Issue#1088). */
719 if (header->tzh_version >= '2')
721 /* Skip ahead to the newer 64-bit data if it's available. */
722 header = (const struct tzhead *)
723 (((const gchar *) (header + 1)) +
724 guint32_from_be(header->tzh_ttisgmtcnt) +
725 guint32_from_be(header->tzh_ttisstdcnt) +
726 8 * guint32_from_be(header->tzh_leapcnt) +
727 5 * guint32_from_be(header->tzh_timecnt) +
728 6 * guint32_from_be(header->tzh_typecnt) +
729 guint32_from_be(header->tzh_charcnt));
730 timesize = sizeof (gint64);
732 time_count = guint32_from_be(header->tzh_timecnt);
733 type_count = guint32_from_be(header->tzh_typecnt);
735 if (header->tzh_version >= '2')
737 const gchar *footer = (((const gchar *) (header + 1))
738 + guint32_from_be(header->tzh_ttisgmtcnt)
739 + guint32_from_be(header->tzh_ttisstdcnt)
740 + 12 * guint32_from_be(header->tzh_leapcnt)
743 + guint32_from_be(header->tzh_charcnt));
744 const gchar *footerlast;
746 g_return_if_fail (footer <= data + size - 2 && footer[0] == '\n');
747 footerlast = memchr (footer + 1, '\n', data + size - (footer + 1));
748 g_return_if_fail (footerlast);
749 footerlen = footerlast + 1 - footer;
752 footertz = parse_footertz (footer, footerlen);
753 g_return_if_fail (footertz);
754 extra_type_count = footertz->t_info->len;
755 extra_time_count = footertz->transitions->len;
759 tz_transitions = ((guint8 *) (header) + sizeof (*header));
760 tz_type_index = tz_transitions + timesize * time_count;
761 tz_ttinfo = tz_type_index + time_count;
762 tz_abbrs = tz_ttinfo + sizeof (struct ttinfo) * type_count;
764 gtz->name = g_steal_pointer (&identifier);
765 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo),
766 type_count + extra_type_count);
767 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition),
768 time_count + extra_time_count);
770 for (index = 0; index < type_count; index++)
772 TransitionInfo t_info;
773 struct ttinfo info = ((struct ttinfo*)tz_ttinfo)[index];
774 t_info.gmt_offset = gint32_from_be (info.tt_gmtoff);
775 t_info.is_dst = info.tt_isdst ? TRUE : FALSE;
776 t_info.abbrev = g_strdup ((gchar *) &tz_abbrs[info.tt_abbrind]);
777 g_array_append_val (gtz->t_info, t_info);
780 for (index = 0; index < time_count; index++)
783 if (header->tzh_version >= '2')
784 trans.time = gint64_from_be (((gint64_be*)tz_transitions)[index]);
786 trans.time = gint32_from_be (((gint32_be*)tz_transitions)[index]);
787 last_explicit_transition_time = trans.time;
788 trans.info_index = tz_type_index[index];
789 g_assert (trans.info_index >= 0);
790 g_assert ((guint) trans.info_index < gtz->t_info->len);
791 g_array_append_val (gtz->transitions, trans);
796 /* Append footer time types. Don't bother to coalesce
797 duplicates with existing time types. */
798 for (index = 0; index < extra_type_count; index++)
800 TransitionInfo t_info;
801 TransitionInfo *footer_t_info
802 = &g_array_index (footertz->t_info, TransitionInfo, index);
803 t_info.gmt_offset = footer_t_info->gmt_offset;
804 t_info.is_dst = footer_t_info->is_dst;
805 t_info.abbrev = g_steal_pointer (&footer_t_info->abbrev);
806 g_array_append_val (gtz->t_info, t_info);
809 /* Append footer transitions that follow the last explicit
811 for (index = 0; index < extra_time_count; index++)
813 Transition *footer_transition
814 = &g_array_index (footertz->transitions, Transition, index);
816 || last_explicit_transition_time < footer_transition->time)
819 trans.time = footer_transition->time;
820 trans.info_index = type_count + footer_transition->info_index;
821 g_array_append_val (gtz->transitions, trans);
825 g_time_zone_unref (footertz);
829 #elif defined (G_OS_WIN32)
832 copy_windows_systemtime (SYSTEMTIME *s_time, TimeZoneDate *tzdate)
835 = s_time->wHour * 3600 + s_time->wMinute * 60 + s_time->wSecond;
836 tzdate->mon = s_time->wMonth;
837 tzdate->year = s_time->wYear;
838 tzdate->wday = s_time->wDayOfWeek ? s_time->wDayOfWeek : 7;
842 tzdate->mday = s_time->wDay;
846 tzdate->week = s_time->wDay;
849 /* UTC = local time + bias while local time = UTC + offset */
851 rule_from_windows_time_zone_info (TimeZoneRule *rule,
852 TIME_ZONE_INFORMATION *tzi)
854 gchar *std_name, *dlt_name;
856 std_name = g_utf16_to_utf8 ((gunichar2 *)tzi->StandardName, -1, NULL, NULL, NULL);
857 if (std_name == NULL)
860 dlt_name = g_utf16_to_utf8 ((gunichar2 *)tzi->DaylightName, -1, NULL, NULL, NULL);
861 if (dlt_name == NULL)
868 if (tzi->StandardDate.wMonth)
870 rule->std_offset = -(tzi->Bias + tzi->StandardBias) * 60;
871 rule->dlt_offset = -(tzi->Bias + tzi->DaylightBias) * 60;
872 copy_windows_systemtime (&(tzi->DaylightDate), &(rule->dlt_start));
874 copy_windows_systemtime (&(tzi->StandardDate), &(rule->dlt_end));
879 rule->std_offset = -tzi->Bias * 60;
880 rule->dlt_start.mon = 0;
882 strncpy (rule->std_name, std_name, NAME_SIZE - 1);
883 strncpy (rule->dlt_name, dlt_name, NAME_SIZE - 1);
892 windows_default_tzname (void)
894 const gunichar2 *subkey =
895 L"SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation";
897 gchar *key_name = NULL;
898 gunichar2 *key_name_w = NULL;
899 if (RegOpenKeyExW (HKEY_LOCAL_MACHINE, subkey, 0,
900 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
903 if (RegQueryValueExW (key, L"TimeZoneKeyName", NULL, NULL,
904 NULL, &size) == ERROR_SUCCESS)
906 key_name_w = g_malloc ((gint)size);
908 if (key_name_w == NULL ||
909 RegQueryValueExW (key, L"TimeZoneKeyName", NULL, NULL,
910 (LPBYTE)key_name_w, &size) != ERROR_SUCCESS)
916 key_name = g_utf16_to_utf8 (key_name_w, -1, NULL, NULL, NULL);
928 SYSTEMTIME StandardDate;
929 SYSTEMTIME DaylightDate;
933 system_time_copy (SYSTEMTIME *orig, SYSTEMTIME *target)
935 g_return_if_fail (orig != NULL);
936 g_return_if_fail (target != NULL);
938 target->wYear = orig->wYear;
939 target->wMonth = orig->wMonth;
940 target->wDayOfWeek = orig->wDayOfWeek;
941 target->wDay = orig->wDay;
942 target->wHour = orig->wHour;
943 target->wMinute = orig->wMinute;
944 target->wSecond = orig->wSecond;
945 target->wMilliseconds = orig->wMilliseconds;
949 register_tzi_to_tzi (RegTZI *reg, TIME_ZONE_INFORMATION *tzi)
951 g_return_if_fail (reg != NULL);
952 g_return_if_fail (tzi != NULL);
953 tzi->Bias = reg->Bias;
954 system_time_copy (&(reg->StandardDate), &(tzi->StandardDate));
955 tzi->StandardBias = reg->StandardBias;
956 system_time_copy (&(reg->DaylightDate), &(tzi->DaylightDate));
957 tzi->DaylightBias = reg->DaylightBias;
961 rules_from_windows_time_zone (const gchar *identifier,
962 const gchar *resolved_identifier,
963 TimeZoneRule **rules)
966 gchar *subkey = NULL;
967 gchar *subkey_dynamic = NULL;
968 const gchar *key_name;
969 const gchar *reg_key =
970 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\";
971 TIME_ZONE_INFORMATION tzi;
974 RegTZI regtzi = { 0 }, regtzi_prev;
975 WCHAR winsyspath[MAX_PATH];
976 gunichar2 *subkey_w, *subkey_dynamic_w;
978 subkey_dynamic_w = NULL;
980 if (GetSystemDirectoryW (winsyspath, MAX_PATH) == 0)
983 g_assert (rules != NULL);
989 key_name = resolved_identifier;
991 key_name = identifier;
996 subkey = g_strconcat (reg_key, key_name, NULL);
997 subkey_w = g_utf8_to_utf16 (subkey, -1, NULL, NULL, NULL);
998 if (subkey_w == NULL)
999 goto utf16_conv_failed;
1001 subkey_dynamic = g_strconcat (subkey, "\\Dynamic DST", NULL);
1002 subkey_dynamic_w = g_utf8_to_utf16 (subkey_dynamic, -1, NULL, NULL, NULL);
1003 if (subkey_dynamic_w == NULL)
1004 goto utf16_conv_failed;
1006 if (RegOpenKeyExW (HKEY_LOCAL_MACHINE, subkey_w, 0,
1007 KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
1008 goto utf16_conv_failed;
1010 size = sizeof tzi.StandardName;
1012 /* use RegLoadMUIStringW() to query MUI_Std from the registry if possible, otherwise
1013 fallback to querying Std */
1014 if (RegLoadMUIStringW (key, L"MUI_Std", tzi.StandardName,
1015 size, &size, 0, winsyspath) != ERROR_SUCCESS)
1017 size = sizeof tzi.StandardName;
1018 if (RegQueryValueExW (key, L"Std", NULL, NULL,
1019 (LPBYTE)&(tzi.StandardName), &size) != ERROR_SUCCESS)
1020 goto registry_failed;
1023 size = sizeof tzi.DaylightName;
1025 /* use RegLoadMUIStringW() to query MUI_Dlt from the registry if possible, otherwise
1026 fallback to querying Dlt */
1027 if (RegLoadMUIStringW (key, L"MUI_Dlt", tzi.DaylightName,
1028 size, &size, 0, winsyspath) != ERROR_SUCCESS)
1030 size = sizeof tzi.DaylightName;
1031 if (RegQueryValueExW (key, L"Dlt", NULL, NULL,
1032 (LPBYTE)&(tzi.DaylightName), &size) != ERROR_SUCCESS)
1033 goto registry_failed;
1037 if (RegOpenKeyExW (HKEY_LOCAL_MACHINE, subkey_dynamic_w, 0,
1038 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
1040 DWORD i, first, last, year;
1043 size = sizeof first;
1044 if (RegQueryValueExW (key, L"FirstEntry", NULL, NULL,
1045 (LPBYTE) &first, &size) != ERROR_SUCCESS)
1046 goto registry_failed;
1049 if (RegQueryValueExW (key, L"LastEntry", NULL, NULL,
1050 (LPBYTE) &last, &size) != ERROR_SUCCESS)
1051 goto registry_failed;
1053 rules_num = last - first + 2;
1054 *rules = g_new0 (TimeZoneRule, rules_num);
1056 for (year = first, i = 0; *rules != NULL && year <= last; year++)
1058 gboolean failed = FALSE;
1059 swprintf_s (s, 11, L"%d", year);
1063 size = sizeof regtzi;
1064 if (RegQueryValueExW (key, s, NULL, NULL,
1065 (LPBYTE) ®tzi, &size) != ERROR_SUCCESS)
1076 if (year > first && memcmp (®tzi_prev, ®tzi, sizeof regtzi) == 0)
1079 memcpy (®tzi_prev, ®tzi, sizeof regtzi);
1081 register_tzi_to_tzi (®tzi, &tzi);
1083 if (!rule_from_windows_time_zone_info (&(*rules)[i], &tzi))
1090 (*rules)[i++].start_year = year;
1098 else if (RegOpenKeyExW (HKEY_LOCAL_MACHINE, subkey_w, 0,
1099 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
1101 size = sizeof regtzi;
1102 if (RegQueryValueExW (key, L"TZI", NULL, NULL,
1103 (LPBYTE) ®tzi, &size) == ERROR_SUCCESS)
1106 *rules = g_new0 (TimeZoneRule, 2);
1107 register_tzi_to_tzi (®tzi, &tzi);
1109 if (!rule_from_windows_time_zone_info (&(*rules)[0], &tzi))
1120 g_free (subkey_dynamic_w);
1121 g_free (subkey_dynamic);
1127 (*rules)[0].start_year = MIN_TZYEAR;
1128 if ((*rules)[rules_num - 2].start_year < MAX_TZYEAR)
1129 (*rules)[rules_num - 1].start_year = MAX_TZYEAR;
1131 (*rules)[rules_num - 1].start_year = (*rules)[rules_num - 2].start_year + 1;
1142 find_relative_date (TimeZoneDate *buffer)
1146 g_date_clear (&date, 1);
1147 wday = buffer->wday;
1149 /* Get last day if last is needed, first day otherwise */
1150 if (buffer->mon == 13 || buffer->mon == 14) /* Julian Date */
1152 g_date_set_dmy (&date, 1, 1, buffer->year);
1153 if (wday >= 59 && buffer->mon == 13 && g_date_is_leap_year (buffer->year))
1154 g_date_add_days (&date, wday);
1156 g_date_add_days (&date, wday - 1);
1157 buffer->mon = (int) g_date_get_month (&date);
1158 buffer->mday = (int) g_date_get_day (&date);
1164 guint days_in_month = g_date_get_days_in_month (buffer->mon, buffer->year);
1165 GDateWeekday first_wday;
1167 g_date_set_dmy (&date, 1, buffer->mon, buffer->year);
1168 first_wday = g_date_get_weekday (&date);
1170 if ((guint) first_wday > wday)
1172 /* week is 1 <= w <= 5, we need 0-based */
1173 days = 7 * (buffer->week - 1) + wday - first_wday;
1175 /* "days" is a 0-based offset from the 1st of the month.
1176 * Adding days == days_in_month would bring us into the next month,
1177 * hence the ">=" instead of just ">".
1179 while (days >= days_in_month)
1182 g_date_add_days (&date, days);
1184 buffer->mday = g_date_get_day (&date);
1188 /* Offset is previous offset of local time. Returns 0 if month is 0 */
1190 boundary_for_year (TimeZoneDate *boundary,
1194 TimeZoneDate buffer;
1196 const guint64 unix_epoch_start = 719163L;
1197 const guint64 seconds_per_day = 86400L;
1203 if (boundary->year == 0)
1208 find_relative_date (&buffer);
1211 g_assert (buffer.year == year);
1212 g_date_clear (&date, 1);
1213 g_date_set_dmy (&date, buffer.mday, buffer.mon, buffer.year);
1214 return ((g_date_get_julian (&date) - unix_epoch_start) * seconds_per_day +
1215 buffer.offset - offset);
1219 fill_transition_info_from_rule (TransitionInfo *info,
1223 gint offset = is_dst ? rule->dlt_offset : rule->std_offset;
1224 gchar *name = is_dst ? rule->dlt_name : rule->std_name;
1226 info->gmt_offset = offset;
1227 info->is_dst = is_dst;
1230 info->abbrev = g_strdup (name);
1233 info->abbrev = g_strdup_printf ("%+03d%02d",
1234 (int) offset / 3600,
1235 (int) abs (offset / 60) % 60);
1239 init_zone_from_rules (GTimeZone *gtz,
1240 TimeZoneRule *rules,
1242 gchar *identifier /* (transfer full) */)
1244 guint type_count = 0, trans_count = 0, info_index = 0;
1245 guint ri; /* rule index */
1246 gboolean skip_first_std_trans = TRUE;
1252 /* Last rule only contains max year */
1253 for (ri = 0; ri < rules_num - 1; ri++)
1255 if (rules[ri].dlt_start.mon || rules[ri].dlt_end.mon)
1257 guint rulespan = (rules[ri + 1].start_year - rules[ri].start_year);
1258 guint transitions = rules[ri].dlt_start.mon > 0 ? 1 : 0;
1259 transitions += rules[ri].dlt_end.mon > 0 ? 1 : 0;
1260 type_count += rules[ri].dlt_start.mon > 0 ? 2 : 1;
1261 trans_count += transitions * rulespan;
1267 gtz->name = g_steal_pointer (&identifier);
1268 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), type_count);
1269 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition), trans_count);
1271 last_offset = rules[0].std_offset;
1273 for (ri = 0; ri < rules_num - 1; ri++)
1275 if ((rules[ri].std_offset || rules[ri].dlt_offset) &&
1276 rules[ri].dlt_start.mon == 0 && rules[ri].dlt_end.mon == 0)
1278 TransitionInfo std_info;
1280 fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
1281 g_array_append_val (gtz->t_info, std_info);
1284 ((rules[ri - 1].dlt_start.mon > 12 &&
1285 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
1286 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
1288 /* The previous rule was a southern hemisphere rule that
1289 starts the year with DST, so we need to add a
1290 transition to return to standard time */
1291 guint year = rules[ri].start_year;
1292 gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
1294 Transition std_trans = {std_time, info_index};
1295 g_array_append_val (gtz->transitions, std_trans);
1298 last_offset = rules[ri].std_offset;
1300 skip_first_std_trans = TRUE;
1304 const guint start_year = rules[ri].start_year;
1305 const guint end_year = rules[ri + 1].start_year;
1308 TransitionInfo std_info, dlt_info;
1309 if (rules[ri].dlt_start.mon > 12)
1310 dlt_first = rules[ri].dlt_start.wday > rules[ri].dlt_end.wday;
1312 dlt_first = rules[ri].dlt_start.mon > rules[ri].dlt_end.mon;
1313 /* Standard rules are always even, because before the first
1314 transition is always standard time, and 0 is even. */
1315 fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
1316 fill_transition_info_from_rule (&dlt_info, &(rules[ri]), TRUE);
1318 g_array_append_val (gtz->t_info, std_info);
1319 g_array_append_val (gtz->t_info, dlt_info);
1321 /* Transition dates. We hope that a year which ends daylight
1322 time in a southern-hemisphere country (i.e., one that
1323 begins the year in daylight time) will include a rule
1324 which has only a dlt_end. */
1325 for (year = start_year; year < end_year; year++)
1327 gint32 dlt_offset = (dlt_first ? last_offset :
1328 rules[ri].dlt_offset);
1329 gint32 std_offset = (dlt_first ? rules[ri].std_offset :
1331 /* NB: boundary_for_year returns 0 if mon == 0 */
1332 gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
1334 gint64 dlt_time = boundary_for_year (&rules[ri].dlt_start,
1336 Transition std_trans = {std_time, info_index};
1337 Transition dlt_trans = {dlt_time, info_index + 1};
1338 last_offset = (dlt_first ? rules[ri].dlt_offset :
1339 rules[ri].std_offset);
1342 if (skip_first_std_trans)
1343 skip_first_std_trans = FALSE;
1345 g_array_append_val (gtz->transitions, std_trans);
1347 g_array_append_val (gtz->transitions, dlt_trans);
1352 g_array_append_val (gtz->transitions, dlt_trans);
1354 g_array_append_val (gtz->transitions, std_trans);
1362 ((rules[ri - 1].dlt_start.mon > 12 &&
1363 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
1364 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
1366 /* The previous rule was a southern hemisphere rule that
1367 starts the year with DST, so we need to add a
1368 transition to return to standard time */
1369 TransitionInfo info;
1370 guint year = rules[ri].start_year;
1372 fill_transition_info_from_rule (&info, &(rules[ri - 1]), FALSE);
1373 g_array_append_val (gtz->t_info, info);
1374 trans.time = boundary_for_year (&rules[ri - 1].dlt_end,
1376 trans.info_index = info_index;
1377 g_array_append_val (gtz->transitions, trans);
1382 * parses date[/time] for parsing TZ environment variable
1384 * date is either Mm.w.d, Jn or N
1391 * time is either h or hh[[:]mm[[[:]ss]]]
1397 parse_mwd_boundary (gchar **pos, TimeZoneDate *boundary)
1399 gint month, week, day;
1401 if (**pos == '\0' || **pos < '0' || '9' < **pos)
1404 month = *(*pos)++ - '0';
1406 if ((month == 1 && **pos >= '0' && '2' >= **pos) ||
1407 (month == 0 && **pos >= '0' && '9' >= **pos))
1410 month += *(*pos)++ - '0';
1413 if (*(*pos)++ != '.' || month == 0)
1416 if (**pos == '\0' || **pos < '1' || '5' < **pos)
1419 week = *(*pos)++ - '0';
1421 if (*(*pos)++ != '.')
1424 if (**pos == '\0' || **pos < '0' || '6' < **pos)
1427 day = *(*pos)++ - '0';
1433 boundary->mon = month;
1434 boundary->week = week;
1435 boundary->wday = day;
1440 * This parses two slightly different ways of specifying
1443 * - ignore_leap == TRUE
1445 * Jn This specifies the Julian day with n between 1 and 365. Leap days
1446 * are not counted. In this format, February 29 can't be represented;
1447 * February 28 is day 59, and March 1 is always day 60.
1449 * - ignore_leap == FALSE
1451 * n This specifies the zero-based Julian day with n between 0 and 365.
1452 * February 29 is counted in leap years.
1455 parse_julian_boundary (gchar** pos, TimeZoneDate *boundary,
1456 gboolean ignore_leap)
1461 while (**pos >= '0' && '9' >= **pos)
1464 day += *(*pos)++ - '0';
1469 if (day < 1 || 365 < day)
1476 if (day < 0 || 365 < day)
1478 /* GDate wants day in range 1->366 */
1482 g_date_clear (&date, 1);
1483 g_date_set_julian (&date, day);
1485 boundary->mon = (int) g_date_get_month (&date);
1486 boundary->mday = (int) g_date_get_day (&date);
1493 parse_tz_boundary (const gchar *identifier,
1494 TimeZoneDate *boundary)
1498 pos = (gchar*)identifier;
1499 /* Month-week-weekday */
1503 if (!parse_mwd_boundary (&pos, boundary))
1506 /* Julian date which ignores Feb 29 in leap years */
1507 else if (*pos == 'J')
1510 if (!parse_julian_boundary (&pos, boundary, TRUE))
1513 /* Julian date which counts Feb 29 in leap years */
1514 else if (*pos >= '0' && '9' >= *pos)
1516 if (!parse_julian_boundary (&pos, boundary, FALSE))
1525 return parse_constant_offset (pos + 1, &boundary->offset, TRUE);
1528 boundary->offset = 2 * 60 * 60;
1529 return *pos == '\0';
1534 create_ruleset_from_rule (TimeZoneRule **rules, TimeZoneRule *rule)
1536 *rules = g_new0 (TimeZoneRule, 2);
1538 (*rules)[0].start_year = MIN_TZYEAR;
1539 (*rules)[1].start_year = MAX_TZYEAR;
1541 (*rules)[0].std_offset = -rule->std_offset;
1542 (*rules)[0].dlt_offset = -rule->dlt_offset;
1543 (*rules)[0].dlt_start = rule->dlt_start;
1544 (*rules)[0].dlt_end = rule->dlt_end;
1545 strcpy ((*rules)[0].std_name, rule->std_name);
1546 strcpy ((*rules)[0].dlt_name, rule->dlt_name);
1551 parse_offset (gchar **pos, gint32 *target)
1554 gchar *target_pos = *pos;
1557 while (**pos == '+' || **pos == '-' || **pos == ':' ||
1558 (**pos >= '0' && '9' >= **pos))
1561 buffer = g_strndup (target_pos, *pos - target_pos);
1562 ret = parse_constant_offset (buffer, target, FALSE);
1569 parse_identifier_boundary (gchar **pos, TimeZoneDate *target)
1572 gchar *target_pos = *pos;
1575 while (**pos != ',' && **pos != '\0')
1577 buffer = g_strndup (target_pos, *pos - target_pos);
1578 ret = parse_tz_boundary (buffer, target);
1585 set_tz_name (gchar **pos, gchar *buffer, guint size)
1587 gboolean quoted = **pos == '<';
1588 gchar *name_pos = *pos;
1591 g_assert (size != 0);
1598 while (g_ascii_isalnum (**pos) || **pos == '-' || **pos == '+');
1603 while (g_ascii_isalpha (**pos))
1606 /* Name should be three or more characters */
1607 /* FIXME: Should return FALSE if the name is too long.
1608 This should simplify code later in this function. */
1609 if (*pos - name_pos < 3)
1612 memset (buffer, 0, size);
1613 /* name_pos isn't 0-terminated, so we have to limit the length expressly */
1614 len = (guint) (*pos - name_pos) > size - 1 ? size - 1 : (guint) (*pos - name_pos);
1615 strncpy (buffer, name_pos, len);
1621 parse_identifier_boundaries (gchar **pos, TimeZoneRule *tzr)
1623 if (*(*pos)++ != ',')
1627 if (!parse_identifier_boundary (pos, &(tzr->dlt_start)) || *(*pos)++ != ',')
1631 if (!parse_identifier_boundary (pos, &(tzr->dlt_end)))
1637 * Creates an array of TimeZoneRule from a TZ environment variable
1638 * type of identifier. Should free rules afterwards
1641 rules_from_identifier (const gchar *identifier,
1642 TimeZoneRule **rules)
1647 g_assert (rules != NULL);
1654 pos = (gchar*)identifier;
1655 memset (&tzr, 0, sizeof (tzr));
1656 /* Standard offset */
1657 if (!(set_tz_name (&pos, tzr.std_name, NAME_SIZE)) ||
1658 !parse_offset (&pos, &(tzr.std_offset)))
1663 return create_ruleset_from_rule (rules, &tzr);
1667 if (!(set_tz_name (&pos, tzr.dlt_name, NAME_SIZE)))
1669 parse_offset (&pos, &(tzr.dlt_offset));
1670 if (tzr.dlt_offset == 0) /* No daylight offset given, assume it's 1
1671 hour earlier that standard */
1672 tzr.dlt_offset = tzr.std_offset - 3600;
1675 /* Windows allows us to use the US DST boundaries if they're not given */
1677 guint i, rules_num = 0;
1679 /* Use US rules, Windows' default is Pacific Standard Time */
1680 if ((rules_num = rules_from_windows_time_zone ("Pacific Standard Time",
1684 for (i = 0; i < rules_num - 1; i++)
1686 (*rules)[i].std_offset = - tzr.std_offset;
1687 (*rules)[i].dlt_offset = - tzr.dlt_offset;
1688 strcpy ((*rules)[i].std_name, tzr.std_name);
1689 strcpy ((*rules)[i].dlt_name, tzr.dlt_name);
1700 /* Start and end required (format 2) */
1701 if (!parse_identifier_boundaries (&pos, &tzr))
1704 return create_ruleset_from_rule (rules, &tzr);
1709 parse_footertz (const gchar *footer, size_t footerlen)
1711 gchar *tzstring = g_strndup (footer + 1, footerlen - 2);
1712 GTimeZone *footertz = NULL;
1714 /* FIXME: The allocation for tzstring could be avoided by
1715 passing a gsize identifier_len argument to rules_from_identifier
1716 and changing the code in that function to stop assuming that
1717 identifier is nul-terminated. */
1718 TimeZoneRule *rules;
1719 guint rules_num = rules_from_identifier (tzstring, &rules);
1724 footertz = g_slice_new0 (GTimeZone);
1725 init_zone_from_rules (footertz, rules, rules_num, NULL);
1726 footertz->ref_count++;
1733 /* Construction {{{1 */
1736 * @identifier: (nullable): a timezone identifier
1738 * A version of g_time_zone_new_identifier() which returns the UTC time zone
1739 * if @identifier could not be parsed or loaded.
1741 * If you need to check whether @identifier was loaded successfully, use
1742 * g_time_zone_new_identifier().
1744 * Returns: (transfer full) (not nullable): the requested timezone
1745 * Deprecated: 2.68: Use g_time_zone_new_identifier() instead, as it provides
1746 * error reporting. Change your code to handle a potentially %NULL return
1752 g_time_zone_new (const gchar *identifier)
1754 GTimeZone *tz = g_time_zone_new_identifier (identifier);
1756 /* Always fall back to UTC. */
1758 tz = g_time_zone_new_utc ();
1760 g_assert (tz != NULL);
1762 return g_steal_pointer (&tz);
1766 * g_time_zone_new_identifier:
1767 * @identifier: (nullable): a timezone identifier
1769 * Creates a #GTimeZone corresponding to @identifier. If @identifier cannot be
1770 * parsed or loaded, %NULL is returned.
1772 * @identifier can either be an RFC3339/ISO 8601 time offset or
1773 * something that would pass as a valid value for the `TZ` environment
1774 * variable (including %NULL).
1776 * In Windows, @identifier can also be the unlocalized name of a time
1777 * zone for standard time, for example "Pacific Standard Time".
1779 * Valid RFC3339 time offsets are `"Z"` (for UTC) or
1780 * `"±hh:mm"`. ISO 8601 additionally specifies
1781 * `"±hhmm"` and `"±hh"`. Offsets are
1782 * time values to be added to Coordinated Universal Time (UTC) to get
1785 * In UNIX, the `TZ` environment variable typically corresponds
1786 * to the name of a file in the zoneinfo database, an absolute path to a file
1787 * somewhere else, or a string in
1788 * "std offset [dst [offset],start[/time],end[/time]]" (POSIX) format.
1789 * There are no spaces in the specification. The name of standard
1790 * and daylight savings time zone must be three or more alphabetic
1791 * characters. Offsets are time values to be added to local time to
1792 * get Coordinated Universal Time (UTC) and should be
1793 * `"[±]hh[[:]mm[:ss]]"`. Dates are either
1794 * `"Jn"` (Julian day with n between 1 and 365, leap
1795 * years not counted), `"n"` (zero-based Julian day
1796 * with n between 0 and 365) or `"Mm.w.d"` (day d
1797 * (0 <= d <= 6) of week w (1 <= w <= 5) of month m (1 <= m <= 12), day
1798 * 0 is a Sunday). Times are in local wall clock time, the default is
1801 * In Windows, the "tzn[+|–]hh[:mm[:ss]][dzn]" format is used, but also
1802 * accepts POSIX format. The Windows format uses US rules for all time
1803 * zones; daylight savings time is 60 minutes behind the standard time
1804 * with date and time of change taken from Pacific Standard Time.
1805 * Offsets are time values to be added to the local time to get
1806 * Coordinated Universal Time (UTC).
1808 * g_time_zone_new_local() calls this function with the value of the
1809 * `TZ` environment variable. This function itself is independent of
1810 * the value of `TZ`, but if @identifier is %NULL then `/etc/localtime`
1811 * will be consulted to discover the correct time zone on UNIX and the
1812 * registry will be consulted or GetTimeZoneInformation() will be used
1813 * to get the local time zone on Windows.
1815 * If intervals are not available, only time zone rules from `TZ`
1816 * environment variable or other means, then they will be computed
1817 * from year 1900 to 2037. If the maximum year for the rules is
1818 * available and it is greater than 2037, then it will followed
1822 * [RFC3339 §5.6](http://tools.ietf.org/html/rfc3339#section-5.6)
1823 * for a precise definition of valid RFC3339 time offsets
1824 * (the `time-offset` expansion) and ISO 8601 for the
1825 * full list of valid time offsets. See
1826 * [The GNU C Library manual](http://www.gnu.org/s/libc/manual/html_node/TZ-Variable.html)
1827 * for an explanation of the possible
1828 * values of the `TZ` environment variable. See
1829 * [Microsoft Time Zone Index Values](http://msdn.microsoft.com/en-us/library/ms912391%28v=winembedded.11%29.aspx)
1830 * for the list of time zones on Windows.
1832 * You should release the return value by calling g_time_zone_unref()
1833 * when you are done with it.
1835 * Returns: (transfer full) (nullable): the requested timezone, or %NULL on
1840 g_time_zone_new_identifier (const gchar *identifier)
1842 GTimeZone *tz = NULL;
1843 TimeZoneRule *rules;
1845 gchar *resolved_identifier = NULL;
1849 G_LOCK (time_zones);
1850 if (time_zones == NULL)
1851 time_zones = g_hash_table_new (g_str_hash, g_str_equal);
1853 tz = g_hash_table_lookup (time_zones, identifier);
1856 g_atomic_int_inc (&tz->ref_count);
1857 G_UNLOCK (time_zones);
1861 resolved_identifier = g_strdup (identifier);
1865 G_LOCK (tz_default);
1867 resolved_identifier = zone_identifier_unix ();
1868 #elif defined (G_OS_WIN32)
1869 resolved_identifier = windows_default_tzname ();
1873 /* Flush default if changed. If the identifier couldn’t be resolved,
1874 * we’re going to fall back to UTC eventually, so don’t clear out the
1875 * cache if it’s already UTC. */
1876 if (!(resolved_identifier == NULL && g_str_equal (tz_default->name, "UTC")) &&
1877 g_strcmp0 (tz_default->name, resolved_identifier) != 0)
1879 g_clear_pointer (&tz_default, g_time_zone_unref);
1883 tz = g_time_zone_ref (tz_default);
1884 G_UNLOCK (tz_default);
1886 g_free (resolved_identifier);
1892 tz = g_slice_new0 (GTimeZone);
1895 zone_for_constant_offset (tz, identifier);
1897 if (tz->t_info == NULL &&
1898 (rules_num = rules_from_identifier (identifier, &rules)))
1900 init_zone_from_rules (tz, rules, rules_num, g_steal_pointer (&resolved_identifier));
1904 if (tz->t_info == NULL)
1907 GBytes *zoneinfo = zone_info_unix (identifier, resolved_identifier);
1908 if (zoneinfo != NULL)
1910 init_zone_from_iana_info (tz, zoneinfo, g_steal_pointer (&resolved_identifier));
1911 g_bytes_unref (zoneinfo);
1913 #elif defined (G_OS_WIN32)
1914 if ((rules_num = rules_from_windows_time_zone (identifier,
1915 resolved_identifier,
1918 init_zone_from_rules (tz, rules, rules_num, g_steal_pointer (&resolved_identifier));
1924 #if defined (G_OS_WIN32)
1925 if (tz->t_info == NULL)
1927 if (identifier == NULL)
1929 TIME_ZONE_INFORMATION tzi;
1931 if (GetTimeZoneInformation (&tzi) != TIME_ZONE_ID_INVALID)
1933 rules = g_new0 (TimeZoneRule, 2);
1935 if (rule_from_windows_time_zone_info (&rules[0], &tzi))
1937 memset (rules[0].std_name, 0, NAME_SIZE);
1938 memset (rules[0].dlt_name, 0, NAME_SIZE);
1940 rules[0].start_year = MIN_TZYEAR;
1941 rules[1].start_year = MAX_TZYEAR;
1943 init_zone_from_rules (tz, rules, 2, g_steal_pointer (&resolved_identifier));
1952 g_free (resolved_identifier);
1954 /* Failed to load the timezone. */
1955 if (tz->t_info == NULL)
1957 g_slice_free (GTimeZone, tz);
1960 G_UNLOCK (time_zones);
1962 G_UNLOCK (tz_default);
1967 g_assert (tz->name != NULL);
1968 g_assert (tz->t_info != NULL);
1971 g_hash_table_insert (time_zones, tz->name, tz);
1974 /* Caching reference */
1975 g_atomic_int_inc (&tz->ref_count);
1979 g_atomic_int_inc (&tz->ref_count);
1982 G_UNLOCK (time_zones);
1984 G_UNLOCK (tz_default);
1990 * g_time_zone_new_utc:
1992 * Creates a #GTimeZone corresponding to UTC.
1994 * This is equivalent to calling g_time_zone_new() with a value like
1995 * "Z", "UTC", "+00", etc.
1997 * You should release the return value by calling g_time_zone_unref()
1998 * when you are done with it.
2000 * Returns: the universal timezone
2005 g_time_zone_new_utc (void)
2007 static GTimeZone *utc = NULL;
2008 static gsize initialised;
2010 if (g_once_init_enter (&initialised))
2012 utc = g_time_zone_new_identifier ("UTC");
2013 g_assert (utc != NULL);
2014 g_once_init_leave (&initialised, TRUE);
2017 return g_time_zone_ref (utc);
2021 * g_time_zone_new_local:
2023 * Creates a #GTimeZone corresponding to local time. The local time
2024 * zone may change between invocations to this function; for example,
2025 * if the system administrator changes it.
2027 * This is equivalent to calling g_time_zone_new() with the value of
2028 * the `TZ` environment variable (including the possibility of %NULL).
2030 * You should release the return value by calling g_time_zone_unref()
2031 * when you are done with it.
2033 * Returns: the local timezone
2038 g_time_zone_new_local (void)
2040 const gchar *tzenv = g_getenv ("TZ");
2045 /* Is time zone changed and must be flushed? */
2046 if (tz_local && g_strcmp0 (g_time_zone_get_identifier (tz_local), tzenv))
2047 g_clear_pointer (&tz_local, g_time_zone_unref);
2049 if (tz_local == NULL)
2050 tz_local = g_time_zone_new_identifier (tzenv);
2051 if (tz_local == NULL)
2052 tz_local = g_time_zone_new_utc ();
2054 tz = g_time_zone_ref (tz_local);
2056 G_UNLOCK (tz_local);
2062 * g_time_zone_new_offset:
2063 * @seconds: offset to UTC, in seconds
2065 * Creates a #GTimeZone corresponding to the given constant offset from UTC,
2068 * This is equivalent to calling g_time_zone_new() with a string in the form
2069 * `[+|-]hh[:mm[:ss]]`.
2071 * It is possible for this function to fail if @seconds is too big (greater than
2072 * 24 hours), in which case this function will return the UTC timezone for
2073 * backwards compatibility. To detect failures like this, use
2074 * g_time_zone_new_identifier() directly.
2076 * Returns: (transfer full): a timezone at the given offset from UTC, or UTC on
2081 g_time_zone_new_offset (gint32 seconds)
2083 GTimeZone *tz = NULL;
2084 gchar *identifier = NULL;
2086 /* Seemingly, we should be using @seconds directly to set the
2087 * #TransitionInfo.gmt_offset to avoid all this string building and parsing.
2088 * However, we always need to set the #GTimeZone.name to a constructed
2089 * string anyway, so we might as well reuse its code.
2090 * g_time_zone_new_identifier() should never fail in this situation. */
2091 identifier = g_strdup_printf ("%c%02u:%02u:%02u",
2092 (seconds >= 0) ? '+' : '-',
2093 (ABS (seconds) / 60) / 60,
2094 (ABS (seconds) / 60) % 60,
2095 ABS (seconds) % 60);
2096 tz = g_time_zone_new_identifier (identifier);
2099 tz = g_time_zone_new_utc ();
2101 g_assert (g_time_zone_get_offset (tz, 0) == seconds);
2103 g_assert (tz != NULL);
2104 g_free (identifier);
2109 #define TRANSITION(n) g_array_index (tz->transitions, Transition, n)
2110 #define TRANSITION_INFO(n) g_array_index (tz->t_info, TransitionInfo, n)
2112 /* Internal helpers {{{1 */
2113 /* NB: Interval 0 is before the first transition, so there's no
2114 * transition structure to point to which TransitionInfo to
2115 * use. Rule-based zones are set up so that TI 0 is always standard
2116 * time (which is what's in effect before Daylight time got started
2117 * in the early 20th century), but IANA tzfiles don't follow that
2118 * convention. The tzfile documentation says to use the first
2119 * standard-time (i.e., non-DST) tinfo, so that's what we do.
2121 inline static const TransitionInfo*
2122 interval_info (GTimeZone *tz,
2126 g_return_val_if_fail (tz->t_info != NULL, NULL);
2127 if (interval && tz->transitions && interval <= tz->transitions->len)
2128 index = (TRANSITION(interval - 1)).info_index;
2131 for (index = 0; index < tz->t_info->len; index++)
2133 TransitionInfo *tzinfo = &(TRANSITION_INFO(index));
2134 if (!tzinfo->is_dst)
2140 return &(TRANSITION_INFO(index));
2143 inline static gint64
2144 interval_start (GTimeZone *tz,
2147 if (!interval || tz->transitions == NULL || tz->transitions->len == 0)
2149 if (interval > tz->transitions->len)
2150 interval = tz->transitions->len;
2151 return (TRANSITION(interval - 1)).time;
2154 inline static gint64
2155 interval_end (GTimeZone *tz,
2158 if (tz->transitions && interval < tz->transitions->len)
2160 gint64 lim = (TRANSITION(interval)).time;
2161 return lim - (lim != G_MININT64);
2166 inline static gint32
2167 interval_offset (GTimeZone *tz,
2170 g_return_val_if_fail (tz->t_info != NULL, 0);
2171 return interval_info (tz, interval)->gmt_offset;
2174 inline static gboolean
2175 interval_isdst (GTimeZone *tz,
2178 g_return_val_if_fail (tz->t_info != NULL, 0);
2179 return interval_info (tz, interval)->is_dst;
2183 inline static gchar*
2184 interval_abbrev (GTimeZone *tz,
2187 g_return_val_if_fail (tz->t_info != NULL, 0);
2188 return interval_info (tz, interval)->abbrev;
2191 inline static gint64
2192 interval_local_start (GTimeZone *tz,
2196 return interval_start (tz, interval) + interval_offset (tz, interval);
2201 inline static gint64
2202 interval_local_end (GTimeZone *tz,
2205 if (tz->transitions && interval < tz->transitions->len)
2206 return interval_end (tz, interval) + interval_offset (tz, interval);
2212 interval_valid (GTimeZone *tz,
2215 if ( tz->transitions == NULL)
2216 return interval == 0;
2217 return interval <= tz->transitions->len;
2220 /* g_time_zone_find_interval() {{{1 */
2223 * g_time_zone_adjust_time:
2225 * @type: the #GTimeType of @time_
2226 * @time_: a pointer to a number of seconds since January 1, 1970
2228 * Finds an interval within @tz that corresponds to the given @time_,
2229 * possibly adjusting @time_ if required to fit into an interval.
2230 * The meaning of @time_ depends on @type.
2232 * This function is similar to g_time_zone_find_interval(), with the
2233 * difference that it always succeeds (by making the adjustments
2236 * In any of the cases where g_time_zone_find_interval() succeeds then
2237 * this function returns the same value, without modifying @time_.
2239 * This function may, however, modify @time_ in order to deal with
2240 * non-existent times. If the non-existent local @time_ of 02:30 were
2241 * requested on March 14th 2010 in Toronto then this function would
2242 * adjust @time_ to be 03:00 and return the interval containing the
2245 * Returns: the interval containing @time_, never -1
2250 g_time_zone_adjust_time (GTimeZone *tz,
2255 gboolean interval_is_dst;
2257 if (tz->transitions == NULL)
2260 intervals = tz->transitions->len;
2262 /* find the interval containing *time UTC
2263 * TODO: this could be binary searched (or better) */
2264 for (i = 0; i <= intervals; i++)
2265 if (*time_ <= interval_end (tz, i))
2268 g_assert (interval_start (tz, i) <= *time_ && *time_ <= interval_end (tz, i));
2270 if (type != G_TIME_TYPE_UNIVERSAL)
2272 if (*time_ < interval_local_start (tz, i))
2273 /* if time came before the start of this interval... */
2277 /* if it's not in the previous interval... */
2278 if (*time_ > interval_local_end (tz, i))
2280 /* it doesn't exist. fast-forward it. */
2282 *time_ = interval_local_start (tz, i);
2286 else if (*time_ > interval_local_end (tz, i))
2287 /* if time came after the end of this interval... */
2291 /* if it's not in the next interval... */
2292 if (*time_ < interval_local_start (tz, i))
2293 /* it doesn't exist. fast-forward it. */
2294 *time_ = interval_local_start (tz, i);
2299 interval_is_dst = interval_isdst (tz, i);
2300 if ((interval_is_dst && type != G_TIME_TYPE_DAYLIGHT) ||
2301 (!interval_is_dst && type == G_TIME_TYPE_DAYLIGHT))
2303 /* it's in this interval, but dst flag doesn't match.
2304 * check neighbours for a better fit. */
2305 if (i && *time_ <= interval_local_end (tz, i - 1))
2308 else if (i < intervals &&
2309 *time_ >= interval_local_start (tz, i + 1))
2319 * g_time_zone_find_interval:
2321 * @type: the #GTimeType of @time_
2322 * @time_: a number of seconds since January 1, 1970
2324 * Finds an interval within @tz that corresponds to the given @time_.
2325 * The meaning of @time_ depends on @type.
2327 * If @type is %G_TIME_TYPE_UNIVERSAL then this function will always
2328 * succeed (since universal time is monotonic and continuous).
2330 * Otherwise @time_ is treated as local time. The distinction between
2331 * %G_TIME_TYPE_STANDARD and %G_TIME_TYPE_DAYLIGHT is ignored except in
2332 * the case that the given @time_ is ambiguous. In Toronto, for example,
2333 * 01:30 on November 7th 2010 occurred twice (once inside of daylight
2334 * savings time and the next, an hour later, outside of daylight savings
2335 * time). In this case, the different value of @type would result in a
2336 * different interval being returned.
2338 * It is still possible for this function to fail. In Toronto, for
2339 * example, 02:00 on March 14th 2010 does not exist (due to the leap
2340 * forward to begin daylight savings time). -1 is returned in that
2343 * Returns: the interval containing @time_, or -1 in case of failure
2348 g_time_zone_find_interval (GTimeZone *tz,
2353 gboolean interval_is_dst;
2355 if (tz->transitions == NULL)
2357 intervals = tz->transitions->len;
2358 for (i = 0; i <= intervals; i++)
2359 if (time_ <= interval_end (tz, i))
2362 if (type == G_TIME_TYPE_UNIVERSAL)
2365 if (time_ < interval_local_start (tz, i))
2367 if (time_ > interval_local_end (tz, --i))
2371 else if (time_ > interval_local_end (tz, i))
2373 if (time_ < interval_local_start (tz, ++i))
2379 interval_is_dst = interval_isdst (tz, i);
2380 if ((interval_is_dst && type != G_TIME_TYPE_DAYLIGHT) ||
2381 (!interval_is_dst && type == G_TIME_TYPE_DAYLIGHT))
2383 if (i && time_ <= interval_local_end (tz, i - 1))
2386 else if (i < intervals && time_ >= interval_local_start (tz, i + 1))
2394 /* Public API accessors {{{1 */
2397 * g_time_zone_get_abbreviation:
2399 * @interval: an interval within the timezone
2401 * Determines the time zone abbreviation to be used during a particular
2402 * @interval of time in the time zone @tz.
2404 * For example, in Toronto this is currently "EST" during the winter
2405 * months and "EDT" during the summer months when daylight savings time
2408 * Returns: the time zone abbreviation, which belongs to @tz
2413 g_time_zone_get_abbreviation (GTimeZone *tz,
2416 g_return_val_if_fail (interval_valid (tz, (guint)interval), NULL);
2418 return interval_abbrev (tz, (guint)interval);
2422 * g_time_zone_get_offset:
2424 * @interval: an interval within the timezone
2426 * Determines the offset to UTC in effect during a particular @interval
2427 * of time in the time zone @tz.
2429 * The offset is the number of seconds that you add to UTC time to
2430 * arrive at local time for @tz (ie: negative numbers for time zones
2431 * west of GMT, positive numbers for east).
2433 * Returns: the number of seconds that should be added to UTC to get the
2439 g_time_zone_get_offset (GTimeZone *tz,
2442 g_return_val_if_fail (interval_valid (tz, (guint)interval), 0);
2444 return interval_offset (tz, (guint)interval);
2448 * g_time_zone_is_dst:
2450 * @interval: an interval within the timezone
2452 * Determines if daylight savings time is in effect during a particular
2453 * @interval of time in the time zone @tz.
2455 * Returns: %TRUE if daylight savings time is in effect
2460 g_time_zone_is_dst (GTimeZone *tz,
2463 g_return_val_if_fail (interval_valid (tz, interval), FALSE);
2465 if (tz->transitions == NULL)
2468 return interval_isdst (tz, (guint)interval);
2472 * g_time_zone_get_identifier:
2475 * Get the identifier of this #GTimeZone, as passed to g_time_zone_new().
2476 * If the identifier passed at construction time was not recognised, `UTC` will
2477 * be returned. If it was %NULL, the identifier of the local timezone at
2478 * construction time will be returned.
2480 * The identifier will be returned in the same format as provided at
2481 * construction time: if provided as a time offset, that will be returned by
2484 * Returns: identifier for this timezone
2488 g_time_zone_get_identifier (GTimeZone *tz)
2490 g_return_val_if_fail (tz != NULL, NULL);
2496 /* vim:set foldmethod=marker: */