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"
44 * @short_description: a structure representing a time zone
45 * @see_also: #GDateTime
47 * #GTimeZone is a structure that represents a time zone, at no
48 * particular point in time. It is refcounted and immutable.
50 * A time zone contains a number of intervals. Each interval has
51 * an abbreviation to describe it, an offet to UTC and a flag indicating
52 * if the daylight savings time is in effect during that interval. A
53 * time zone always has at least one interval -- interval 0.
55 * Every UTC time is contained within exactly one interval, but a given
56 * local time may be contained within zero, one or two intervals (due to
57 * incontinuities associated with daylight savings time).
59 * An interval may refer to a specific period of time (eg: the duration
60 * of daylight savings time during 2010) or it may refer to many periods
61 * of time that share the same properties (eg: all periods of daylight
62 * savings time). It is also possible (usually for political reasons)
63 * that some properties (like the abbreviation) change between intervals
64 * without other properties changing.
66 * #GTimeZone is available since GLib 2.26.
72 * #GDateTime is an opaque structure whose members cannot be accessed
78 /* zoneinfo file format {{{1 */
81 typedef struct { gchar bytes[8]; } gint64_be;
82 typedef struct { gchar bytes[4]; } gint32_be;
83 typedef struct { gchar bytes[4]; } guint32_be;
85 static inline gint64 gint64_from_be (const gint64_be be) {
86 gint64 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT64_FROM_BE (tmp);
89 static inline gint32 gint32_from_be (const gint32_be be) {
90 gint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT32_FROM_BE (tmp);
93 static inline guint32 guint32_from_be (const guint32_be be) {
94 guint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GUINT32_FROM_BE (tmp);
101 guchar tzh_reserved[15];
103 guint32_be tzh_ttisgmtcnt;
104 guint32_be tzh_ttisstdcnt;
105 guint32_be tzh_leapcnt;
106 guint32_be tzh_timecnt;
107 guint32_be tzh_typecnt;
108 guint32_be tzh_charcnt;
122 gboolean is_standard;
134 /* GTimeZone structure and lifecycle {{{1 */
143 G_LOCK_DEFINE_STATIC (time_zones);
144 static GHashTable/*<string?, GTimeZone>*/ *time_zones;
150 * Decreases the reference count on @tz.
155 g_time_zone_unref (GTimeZone *tz)
160 ref_count = g_atomic_int_get (&tz->ref_count);
162 g_assert (ref_count > 0);
166 if (tz->name != NULL)
170 /* someone else might have grabbed a ref in the meantime */
171 if G_UNLIKELY (g_atomic_int_get (&tz->ref_count) != 1)
173 G_UNLOCK(time_zones);
177 g_hash_table_remove (time_zones, tz->name);
178 G_UNLOCK(time_zones);
181 g_array_free (tz->t_info, TRUE);
182 if (tz->transitions != NULL)
183 g_array_free (tz->transitions, TRUE);
186 g_slice_free (GTimeZone, tz);
189 else if G_UNLIKELY (!g_atomic_int_compare_and_exchange (&tz->ref_count,
199 * Increases the reference count on @tz.
201 * Returns: a new reference to @tz.
206 g_time_zone_ref (GTimeZone *tz)
208 g_assert (tz->ref_count > 0);
210 g_atomic_int_inc (&tz->ref_count);
215 /* fake zoneinfo creation (for RFC3339/ISO 8601 timezones) {{{1 */
217 * parses strings of the form h or hh[[:]mm[[[:]ss]]] where:
223 parse_time (const gchar *time_,
226 if (*time_ < '0' || '9' < *time_)
229 *offset = 60 * 60 * (*time_++ - '0');
236 if (*time_ < '0' || '9' < *time_)
240 *offset += 60 * 60 * (*time_++ - '0');
242 if (*offset > 23 * 60 * 60)
252 if (*time_ < '0' || '5' < *time_)
255 *offset += 10 * 60 * (*time_++ - '0');
257 if (*time_ < '0' || '9' < *time_)
260 *offset += 60 * (*time_++ - '0');
268 if (*time_ < '0' || '5' < *time_)
271 *offset += 10 * (*time_++ - '0');
273 if (*time_ < '0' || '9' < *time_)
276 *offset += *time_++ - '0';
278 return *time_ == '\0';
282 parse_constant_offset (const gchar *name,
285 if (g_strcmp0 (name, "UTC") == 0)
291 if (*name >= '0' && '9' >= *name)
292 return parse_time (name, offset);
301 return parse_time (name, offset);
304 if (parse_time (name, offset))
316 zone_for_constant_offset (GTimeZone *gtz, const gchar *name)
321 if (name == NULL || !parse_constant_offset (name, &offset))
324 info.gmt_offset = offset;
326 info.is_standard = TRUE;
328 info.abbrev = g_strdup (name);
331 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), 1);
332 g_array_append_val (gtz->t_info, info);
334 /* Constant offset, no transitions */
335 gtz->transitions = NULL;
340 zone_info_unix (const gchar *identifier)
343 GMappedFile *file = NULL;
344 GBytes *zoneinfo = NULL;
346 /* identifier can be a relative or absolute path name;
347 if relative, it is interpreted starting from /usr/share/zoneinfo
348 while the POSIX standard says it should start with :,
349 glibc allows both syntaxes, so we should too */
350 if (identifier != NULL)
354 tzdir = getenv ("TZDIR");
356 tzdir = "/usr/share/zoneinfo";
358 if (*identifier == ':')
361 if (g_path_is_absolute (identifier))
362 filename = g_strdup (identifier);
364 filename = g_build_filename (tzdir, identifier, NULL);
367 filename = g_strdup ("/etc/localtime");
369 file = g_mapped_file_new (filename, FALSE, NULL);
372 zoneinfo = g_bytes_new_with_free_func (g_mapped_file_get_contents (file),
373 g_mapped_file_get_length (file),
374 (GDestroyNotify)g_mapped_file_unref,
375 g_mapped_file_ref (file));
376 g_mapped_file_unref (file);
383 init_zone_from_iana_info (GTimeZone *gtz, GBytes *zoneinfo)
387 guint32 time_count, type_count, leap_count, isgmt_count;
388 guint32 isstd_count, char_count ;
389 gpointer tz_transitions, tz_type_index, tz_ttinfo;
390 gpointer tz_leaps, tz_isgmt, tz_isstd;
392 guint timesize = sizeof (gint32), countsize = sizeof (gint32);
393 const struct tzhead *header = g_bytes_get_data (zoneinfo, &size);
395 g_return_if_fail (size >= sizeof (struct tzhead) &&
396 memcmp (header, "TZif", 4) == 0);
398 if (header->tzh_version == '2')
400 /* Skip ahead to the newer 64-bit data if it's available. */
401 header = (const struct tzhead *)
402 (((const gchar *) (header + 1)) +
403 guint32_from_be(header->tzh_ttisgmtcnt) +
404 guint32_from_be(header->tzh_ttisstdcnt) +
405 8 * guint32_from_be(header->tzh_leapcnt) +
406 5 * guint32_from_be(header->tzh_timecnt) +
407 6 * guint32_from_be(header->tzh_typecnt) +
408 guint32_from_be(header->tzh_charcnt));
409 timesize = sizeof (gint64);
411 time_count = guint32_from_be(header->tzh_timecnt);
412 type_count = guint32_from_be(header->tzh_typecnt);
413 leap_count = guint32_from_be(header->tzh_leapcnt);
414 isgmt_count = guint32_from_be(header->tzh_ttisgmtcnt);
415 isstd_count = guint32_from_be(header->tzh_ttisstdcnt);
416 char_count = guint32_from_be(header->tzh_charcnt);
418 g_assert (type_count == isgmt_count);
419 g_assert (type_count == isstd_count);
421 tz_transitions = (gpointer)(header + 1);
422 tz_type_index = tz_transitions + timesize * time_count;
423 tz_ttinfo = tz_type_index + time_count;
424 tz_abbrs = tz_ttinfo + sizeof (struct ttinfo) * type_count;
425 tz_leaps = tz_abbrs + char_count;
426 tz_isstd = tz_leaps + (timesize + countsize) * leap_count;
427 tz_isgmt = tz_isstd + isstd_count;
429 gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo),
431 gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition),
434 for (index = 0; index < type_count; index++)
436 TransitionInfo t_info;
437 struct ttinfo info = ((struct ttinfo*)tz_ttinfo)[index];
438 t_info.gmt_offset = gint32_from_be (info.tt_gmtoff);
439 t_info.is_dst = info.tt_isdst ? TRUE : FALSE;
440 t_info.is_standard = ((guint8*)tz_isstd)[index] ? TRUE : FALSE;
441 t_info.is_gmt = ((guint8*)tz_isgmt)[index] ? TRUE : FALSE;
442 t_info.abbrev = g_strdup (&tz_abbrs[info.tt_abbrind]);
443 g_array_append_val (gtz->t_info, t_info);
446 for (index = 0; index < time_count; index++)
449 if (header->tzh_version == '2')
450 trans.time = gint64_from_be (((gint64_be*)tz_transitions)[index]);
452 trans.time = gint32_from_be (((gint32_be*)tz_transitions)[index]);
453 trans.info_index = ((guint8*)tz_type_index)[index];
454 g_assert (trans.info_index >= 0);
455 g_assert (trans.info_index < gtz->t_info->len);
456 g_array_append_val (gtz->transitions, trans);
458 g_bytes_unref (zoneinfo);
463 /* Construction {{{1 */
466 * @identifier: (allow-none): a timezone identifier
468 * Creates a #GTimeZone corresponding to @identifier.
470 * @identifier can either be an RFC3339/ISO 8601 time offset or
471 * something that would pass as a valid value for the
472 * <varname>TZ</varname> environment variable (including %NULL).
474 * Valid RFC3339 time offsets are <literal>"Z"</literal> (for UTC) or
475 * <literal>"±hh:mm"</literal>. ISO 8601 additionally specifies
476 * <literal>"±hhmm"</literal> and <literal>"±hh"</literal>.
478 * The <varname>TZ</varname> environment variable typically corresponds
479 * to the name of a file in the zoneinfo database, but there are many
480 * other possibilities. Note that those other possibilities are not
481 * currently implemented, but are planned.
483 * g_time_zone_new_local() calls this function with the value of the
484 * <varname>TZ</varname> environment variable. This function itself is
485 * independent of the value of <varname>TZ</varname>, but if @identifier
486 * is %NULL then <filename>/etc/localtime</filename> will be consulted
487 * to discover the correct timezone.
490 * url='http://tools.ietf.org/html/rfc3339#section-5.6'>RFC3339
491 * §5.6</ulink> for a precise definition of valid RFC3339 time offsets
492 * (the <varname>time-offset</varname> expansion) and ISO 8601 for the
493 * full list of valid time offsets. See <ulink
494 * url='http://www.gnu.org/s/libc/manual/html_node/TZ-Variable.html'>The
495 * GNU C Library manual</ulink> for an explanation of the possible
496 * values of the <varname>TZ</varname> environment variable.
498 * You should release the return value by calling g_time_zone_unref()
499 * when you are done with it.
501 * Returns: the requested timezone
506 g_time_zone_new (const gchar *identifier)
508 GTimeZone *tz = NULL;
511 if (time_zones == NULL)
512 time_zones = g_hash_table_new (g_str_hash, g_str_equal);
516 tz = g_hash_table_lookup (time_zones, identifier);
519 g_atomic_int_inc (&tz->ref_count);
520 G_UNLOCK (time_zones);
525 tz = g_slice_new0 (GTimeZone);
526 tz->name = g_strdup (identifier);
529 zone_for_constant_offset (tz, identifier);
531 if (tz->t_info == NULL)
534 GBytes *zoneinfo = zone_info_unix (identifier);
536 zone_for_constant_offset (tz, "UTC");
539 init_zone_from_iana_info (tz, zoneinfo);
540 g_bytes_unref (zoneinfo);
542 #elif defined G_OS_WIN32
546 if (tz->t_info != NULL)
549 g_hash_table_insert (time_zones, tz->name, tz);
551 g_atomic_int_inc (&tz->ref_count);
552 G_UNLOCK (time_zones);
558 * g_time_zone_new_utc:
560 * Creates a #GTimeZone corresponding to UTC.
562 * This is equivalent to calling g_time_zone_new() with a value like
563 * "Z", "UTC", "+00", etc.
565 * You should release the return value by calling g_time_zone_unref()
566 * when you are done with it.
568 * Returns: the universal timezone
573 g_time_zone_new_utc (void)
575 return g_time_zone_new ("UTC");
579 * g_time_zone_new_local:
581 * Creates a #GTimeZone corresponding to local time. The local time
582 * zone may change between invocations to this function; for example,
583 * if the system administrator changes it.
585 * This is equivalent to calling g_time_zone_new() with the value of the
586 * <varname>TZ</varname> environment variable (including the possibility
589 * You should release the return value by calling g_time_zone_unref()
590 * when you are done with it.
592 * Returns: the local timezone
597 g_time_zone_new_local (void)
599 return g_time_zone_new (getenv ("TZ"));
602 #define TRANSITION(n) g_array_index (tz->transitions, Transition, n)
603 #define TRANSITION_INFO(n) g_array_index (tz->t_info, TransitionInfo, n)
605 /* Internal helpers {{{1 */
606 /* Note that interval 0 is *before* the first transition time, so
607 * interval 1 gets transitions[0].
609 inline static const TransitionInfo*
610 interval_info (GTimeZone *tz,
614 g_return_val_if_fail (tz->t_info != NULL, NULL);
615 if (interval && tz->transitions && interval <= tz->transitions->len)
616 index = (TRANSITION(interval - 1)).info_index;
619 return &(TRANSITION_INFO(index));
623 interval_start (GTimeZone *tz,
626 if (!interval || tz->transitions == NULL || tz->transitions->len == 0)
628 if (interval > tz->transitions->len)
629 interval = tz->transitions->len;
630 return (TRANSITION(interval - 1)).time;
634 interval_end (GTimeZone *tz,
637 if (tz->transitions && interval < tz->transitions->len)
638 return (TRANSITION(interval)).time - 1;
643 interval_offset (GTimeZone *tz,
646 g_return_val_if_fail (tz->t_info != NULL, 0);
647 return interval_info (tz, interval)->gmt_offset;
650 inline static gboolean
651 interval_isdst (GTimeZone *tz,
654 g_return_val_if_fail (tz->t_info != NULL, 0);
655 return interval_info (tz, interval)->is_dst;
659 inline static gboolean
660 interval_isgmt (GTimeZone *tz,
663 g_return_val_if_fail (tz->t_info != NULL, 0);
664 return interval_info (tz, interval)->is_gmt;
667 inline static gboolean
668 interval_isstandard (GTimeZone *tz,
671 return interval_info (tz, interval)->is_standard;
675 interval_abbrev (GTimeZone *tz,
678 g_return_val_if_fail (tz->t_info != NULL, 0);
679 return interval_info (tz, interval)->abbrev;
683 interval_local_start (GTimeZone *tz,
687 return interval_start (tz, interval) + interval_offset (tz, interval);
693 interval_local_end (GTimeZone *tz,
696 if (tz->transitions && interval < tz->transitions->len)
697 return interval_end (tz, interval) + interval_offset (tz, interval);
703 interval_valid (GTimeZone *tz,
706 if ( tz->transitions == NULL)
707 return interval == 0;
708 return interval <= tz->transitions->len;
711 /* g_time_zone_find_interval() {{{1 */
714 * g_time_zone_adjust_time:
716 * @type: the #GTimeType of @time_
717 * @time_: a pointer to a number of seconds since January 1, 1970
719 * Finds an interval within @tz that corresponds to the given @time_,
720 * possibly adjusting @time_ if required to fit into an interval.
721 * The meaning of @time_ depends on @type.
723 * This function is similar to g_time_zone_find_interval(), with the
724 * difference that it always succeeds (by making the adjustments
727 * In any of the cases where g_time_zone_find_interval() succeeds then
728 * this function returns the same value, without modifying @time_.
730 * This function may, however, modify @time_ in order to deal with
731 * non-existent times. If the non-existent local @time_ of 02:30 were
732 * requested on March 14th 2010 in Toronto then this function would
733 * adjust @time_ to be 03:00 and return the interval containing the
736 * Returns: the interval containing @time_, never -1
741 g_time_zone_adjust_time (GTimeZone *tz,
748 if (tz->transitions == NULL)
751 intervals = tz->transitions->len;
753 /* find the interval containing *time UTC
754 * TODO: this could be binary searched (or better) */
755 for (i = 0; i <= intervals; i++)
756 if (*time_ <= interval_end (tz, i))
759 g_assert (interval_start (tz, i) <= *time_ && *time_ <= interval_end (tz, i));
761 if (type != G_TIME_TYPE_UNIVERSAL)
763 if (*time_ < interval_local_start (tz, i))
764 /* if time came before the start of this interval... */
768 /* if it's not in the previous interval... */
769 if (*time_ > interval_local_end (tz, i))
771 /* it doesn't exist. fast-forward it. */
773 *time_ = interval_local_start (tz, i);
777 else if (*time_ > interval_local_end (tz, i))
778 /* if time came after the end of this interval... */
782 /* if it's not in the next interval... */
783 if (*time_ < interval_local_start (tz, i))
784 /* it doesn't exist. fast-forward it. */
785 *time_ = interval_local_start (tz, i);
788 else if (interval_isdst (tz, i) != type)
789 /* it's in this interval, but dst flag doesn't match.
790 * check neighbours for a better fit. */
792 if (i && *time_ <= interval_local_end (tz, i - 1))
795 else if (i < intervals &&
796 *time_ >= interval_local_start (tz, i + 1))
805 * g_time_zone_find_interval:
807 * @type: the #GTimeType of @time_
808 * @time_: a number of seconds since January 1, 1970
810 * Finds an the interval within @tz that corresponds to the given @time_.
811 * The meaning of @time_ depends on @type.
813 * If @type is %G_TIME_TYPE_UNIVERSAL then this function will always
814 * succeed (since universal time is monotonic and continuous).
816 * Otherwise @time_ is treated is local time. The distinction between
817 * %G_TIME_TYPE_STANDARD and %G_TIME_TYPE_DAYLIGHT is ignored except in
818 * the case that the given @time_ is ambiguous. In Toronto, for example,
819 * 01:30 on November 7th 2010 occurred twice (once inside of daylight
820 * savings time and the next, an hour later, outside of daylight savings
821 * time). In this case, the different value of @type would result in a
822 * different interval being returned.
824 * It is still possible for this function to fail. In Toronto, for
825 * example, 02:00 on March 14th 2010 does not exist (due to the leap
826 * forward to begin daylight savings time). -1 is returned in that
829 * Returns: the interval containing @time_, or -1 in case of failure
834 g_time_zone_find_interval (GTimeZone *tz,
841 if (tz->transitions == NULL)
843 intervals = tz->transitions->len;
844 for (i = 0; i <= intervals; i++)
845 if (time_ <= interval_end (tz, i))
848 if (type == G_TIME_TYPE_UNIVERSAL)
851 if (time_ < interval_local_start (tz, i))
853 if (time_ > interval_local_end (tz, --i))
857 else if (time_ > interval_local_end (tz, i))
859 if (time_ < interval_local_start (tz, ++i))
863 else if (interval_isdst (tz, i) != type)
865 if (i && time_ <= interval_local_end (tz, i - 1))
868 else if (i < intervals && time_ >= interval_local_start (tz, i + 1))
875 /* Public API accessors {{{1 */
878 * g_time_zone_get_abbreviation:
880 * @interval: an interval within the timezone
882 * Determines the time zone abbreviation to be used during a particular
883 * @interval of time in the time zone @tz.
885 * For example, in Toronto this is currently "EST" during the winter
886 * months and "EDT" during the summer months when daylight savings time
889 * Returns: the time zone abbreviation, which belongs to @tz
894 g_time_zone_get_abbreviation (GTimeZone *tz,
897 g_return_val_if_fail (interval_valid (tz, (guint)interval), NULL);
899 return interval_abbrev (tz, (guint)interval);
903 * g_time_zone_get_offset:
905 * @interval: an interval within the timezone
907 * Determines the offset to UTC in effect during a particular @interval
908 * of time in the time zone @tz.
910 * The offset is the number of seconds that you add to UTC time to
911 * arrive at local time for @tz (ie: negative numbers for time zones
912 * west of GMT, positive numbers for east).
914 * Returns: the number of seconds that should be added to UTC to get the
920 g_time_zone_get_offset (GTimeZone *tz,
923 g_return_val_if_fail (interval_valid (tz, (guint)interval), 0);
925 return interval_offset (tz, (guint)interval);
929 * g_time_zone_is_dst:
931 * @interval: an interval within the timezone
933 * Determines if daylight savings time is in effect during a particular
934 * @interval of time in the time zone @tz.
936 * Returns: %TRUE if daylight savings time is in effect
941 g_time_zone_is_dst (GTimeZone *tz,
944 g_return_val_if_fail (interval_valid (tz, interval), FALSE);
946 if (tz->transitions == NULL)
949 return interval_isdst (tz, (guint)interval);
953 /* vim:set foldmethod=marker: */