Programming Search⌘K

Conceptcore

Time zone

Also called time zone, timezone, zone, UTC offset, offset from UTC, daylight saving time, DST, summer time, zone ID, IANA zone name, local time.

A time zone is a region with rules that give the offset from UTC at each instant. An offset such as -05:00 is one value of those rules, so an offset is not a zone.

Applies to
core-languages

Idea

A clock on a wall shows local time, and local time differs from place to place. "A time zone is an area which observes a uniform standard time for legal, commercial, and social purposes."1 The difference between local time and UTC is the offset. New York is 5 hours behind UTC in winter, so its offset is -05:00. But in summer New York uses daylight saving time, and its offset is -04:00.

Thus a zone is not one offset. A zone is a set of rules that gives the offset for each instant. Java states the two kinds of value: "There are two distinct types of ID: Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply"2. A program names a region with an identifier of the IANA time zone database, such as America/New_York.

from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

ny = ZoneInfo("America/New_York")
# One zone, two offsets: the rules of New York give -05:00 in winter and -04:00 in summer.
for month in (1, 7):
    t = datetime(2024, month, 9, 12, tzinfo=timezone.utc).astimezone(ny)
    print(t.isoformat(), t.tzname())

# A fixed offset of -05:00 is right for New York in January and wrong in July.
fixed = timezone(timedelta(hours=-5))
print(datetime(2024, 7, 9, 12, tzinfo=timezone.utc).astimezone(fixed).isoformat())

# The same local time in two zones is two different instants.
paris = ZoneInfo("Europe/Paris")
print(datetime(2024, 7, 9, 9, 0, tzinfo=ny) - datetime(2024, 7, 9, 9, 0, tzinfo=paris))
Output
2024-01-09T07:00:00-05:00 EST
2024-07-09T08:00:00-04:00 EDT
2024-07-09T07:00:00-05:00
6:00:00

How it works

Offsets. An offset is a fixed difference from UTC, written as +09:00, -05:00 or Z for zero. Local time is UTC plus the offset. MDN shows the rule as local time = UTC time + offset, and its example is that UTC 1970-01-01T00:00:00 with the offset -05:00 is the local time 1969-12-31T19:00:003. "The offsets range from UTC−12:00 to UTC+14:00, and are usually a whole number of hours, but a few zones are offset by an additional 30 or 45 minutes, such as in India and Nepal."1 An instant with an offset is a complete value: it names one moment. See Date and time values.

Zones. A zone maps each instant to an offset and an abbreviation. In Go, "A Location maps time instants to the zone in use at that time. Typically, the Location represents the collection of time offsets in use in a geographical area."4 The rules come from the tz database, which "attempts to record the history and predicted future of civil time scales."5 Its entries hold the rules over the years. For example, the United States has one rule for daylight saving time from 1987 to 2006 and another rule from 2007 on6. So the offset of a zone depends on the date, and also on the version of the data. See IANA time zone database.

From an instant to local time. This direction is easy: find the rule for the instant, then add its offset. Each instant has exactly one local time in each zone. The Java documentation says: "Obtaining the offset for an instant is simple, as there is exactly one valid offset for each instant."7

From local time to an instant. This direction has three cases, because the clocks jump twice a year. In Java's words: "Normal, with one valid offset."7 Then a gap: "This is when clocks jump forward typically due to the spring daylight savings change from "winter" to "summer". In a gap there are local date-time values with no valid offset."7 And an overlap: "In an overlap there are local date-time values with two valid offsets."7 In New York, 02:30 on 2024-03-10 does not exist, and 01:30 on 2024-11-03 happens two times. A library must pick a rule for each case.

The choice in an overlap. Python adds a flag to a local time. PEP 495 adds an attribute "that can be used to differentiate between two moments in time for which local times are the same."8 Its values are "0 and 1 with 0 corresponding to the earlier and 1 to the later of the two possible readings of an ambiguous local time."8 Java keeps the earlier offset by default and has withLaterOffsetAtOverlap(). C++ has choose::earliest and choose::latest, and Temporal has the option disambiguation.

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaStandard library
CStandard library
C#Standard library
JavaScriptNative
TypeScriptNativeTypeScript uses the JavaScript Intl.DateTimeFormat with the option timeZone, and Temporal.ZonedDateTime where the runtime has it. No example file exists.
GoStandard library
RustLibraryThe Rust standard library has no time zones. SystemTime is an instant only. The crate chrono-tz compiles the IANA data into the program, and the crate jiff reads the zone data of the system. No example file exists because the examples use the standard library only.
KotlinStandard libraryOn the JVM, Kotlin uses java.time.ZoneId, ZoneRules and ZonedDateTime. The library kotlinx-datetime has a TimeZone type with the same IANA names on all platforms. No example file exists because kotlinc is not installed.
SQLNativeStandard SQL has TIMESTAMP WITH TIME ZONE and the AT TIME ZONE expression. Each system differs: PostgreSQL stores an instant in UTC and drops the zone, Oracle can keep a zone region name, and SQLite has no zone type.
BashIdiom
PowerShellStandard libraryGet-TimeZone returns the local zone or a named zone, and PowerShell uses the .NET TimeZoneInfo for conversions, such as [TimeZoneInfo]::ConvertTimeBySystemTimeZoneId(). No example file exists because pwsh is not installed.
HTMLDoes not applyThe datetime attribute of the time element holds an offset in text, not a zone. HTML has no zone rules.
CSSDoes not applyCSS has no dates or time zones.
Regular expressionsDoes not applyA regular expression has no zones. A pattern can only check the text of an offset such as +05:30.
Language Verdict Mechanism
Python stdlib zoneinfo.ZoneInfo for IANA zones and datetime.timezone for fixed offsets; the attribute fold
JavaScript native Intl.DateTimeFormat with the option timeZone; Temporal.ZonedDateTime
TypeScript native the JavaScript Intl and Temporal
Java stdlib ZoneId, ZoneOffset, ZoneRules and ZonedDateTime
Kotlin stdlib java.time on the JVM; TimeZone of kotlinx-datetime
C# stdlib TimeZoneInfo and DateTimeOffset
Go stdlib time.LoadLocation, time.FixedZone and the method In
Rust library no zones in the standard library; the crates chrono-tz and jiff
C stdlib the local zone of the process only, set by the variable TZ; localtime() and mktime()
C++ stdlib std::chrono::time_zone, locate_zone() and zoned_time
Bash idiom the variable TZ for one command or a subshell
PowerShell stdlib Get-TimeZone and the .NET TimeZoneInfo
SQL native TIMESTAMP WITH TIME ZONE and AT TIME ZONE, with different meanings in each system
Regex n/a no zones; a pattern can only match the text of an offset
HTML n/a the datetime attribute of time holds an offset in text, not a zone
CSS n/a no dates or zones

Most standard libraries now read the IANA data. "The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615."9 In Go, LoadLocation takes a name such as America/New_York, which is "a location name corresponding to a file in the IANA Time Zone database"4. In .NET, TimeZoneInfo "Represents any time zone in the world."10 In C++, "The class zoned_time represents a logical pairing of a time zone and a std::chrono::time_point whose resolution is Duration."11

JavaScript has two levels. A Date is an instant, and only Intl.DateTimeFormat can show it in another zone. The newer Temporal.ZonedDateTime "is fundamentally represented as a combination of an instant, a time zone, and a calendar system."3 C has the weakest model: a process has one local zone, which the variable TZ sets, and no zone value exists. The Rust standard library has no zones at all.

SQL uses the name TIMESTAMP WITH TIME ZONE, but in PostgreSQL such a value does not keep a zone: "the value is stored internally as UTC, and the originally stated or assumed time zone is not retained."12

The example files show New York in winter and in summer, and a gap or an overlap in each language that has a zone type.

PythonGitHub
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

ny = ZoneInfo("America/New_York")

# A gap: on 2024-03-10 the clocks in New York jump from 02:00 to 03:00.
gap = datetime(2024, 3, 10, 2, 30, tzinfo=ny)
print(gap.astimezone(timezone.utc).astimezone(ny).isoformat())

# An overlap: on 2024-11-03, 01:30 happens two times. fold picks one of them.
for fold in (0, 1):
    t = datetime(2024, 11, 3, 1, 30, fold=fold, tzinfo=ny)
    print(t.isoformat(), t.tzname(), t.astimezone(timezone.utc).strftime("%H:%M"))

# A zone gives the offset for each instant. A fixed offset does not change.
fixed = timezone(timedelta(hours=-5))
july = datetime(2024, 7, 9, 12, tzinfo=timezone.utc)
print(july.astimezone(ny).isoformat(), july.astimezone(fixed).isoformat())
Output
2024-03-10T03:30:00-04:00
2024-11-03T01:30:00-04:00 EDT 05:30
2024-11-03T01:30:00-05:00 EST 06:30
2024-07-09T08:00:00-04:00 2024-07-09T07:00:00-05:00
  • Verdict: stdlib. zoneinfo.ZoneInfo gives a zone of the IANA database as a tzinfo, and datetime.timezone gives a fixed offset. The attribute fold chooses between the two readings of a local time in an overlap.
#include <chrono>
#include <format>
#include <iostream>

int main() {
    using namespace std::chrono;
    const time_zone* ny = locate_zone("America/New_York");
    for (sys_days d : {sys_days{2024y / January / 9}, sys_days{2024y / July / 9}}) {
        zoned_time z{ny, d + 12h};
        std::cout << std::format("{:%FT%H:%M%z %Z}", z) << '\n';
    }

    // get_info tells whether a local time is in a gap or an overlap.
    local_seconds gap = local_days{2024y / March / 10} + 2h + 30min;
    std::cout << (ny->get_info(gap).result == local_info::nonexistent) << '\n';
    local_seconds over = local_days{2024y / November / 3} + 1h + 30min;
    local_info oi = ny->get_info(over);
    std::cout << (oi.result == local_info::ambiguous) << ' ' << oi.first.offset << ' '
              << oi.second.offset << '\n';

    // choose::latest picks the second of the two instants.
    zoned_time later{ny, over, choose::latest};
    std::cout << std::format("{:%FT%H:%M%z}", later) << '\n';
}
Output
2024-01-09T07:00-0500 EST
2024-07-09T08:00-0400 EDT
1
1 -14400s -18000s
2024-11-03T01:30-0500
  • Verdict: stdlib. std::chrono has time_zone from the IANA database through locate_zone, and zoned_time pairs a zone with a time point. get_info finds gaps and overlaps, and choose::earliest and choose::latest resolve an overlap.
JavaGitHub
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class Main {
  public static void main(String[] args) {
    ZoneId ny = ZoneId.of("America/New_York");
    Instant winter = Instant.parse("2024-01-09T12:00:00Z");
    Instant summer = Instant.parse("2024-07-09T12:00:00Z");
    System.out.println(winter.atZone(ny) + " " + summer.atZone(ny));
    System.out.println(ny.getRules().getOffset(winter) + " " + ny.getRules().getOffset(summer));

    // A gap: the local time moves forward by the length of the gap.
    System.out.println(ZonedDateTime.of(LocalDateTime.of(2024, 3, 10, 2, 30), ny));

    // An overlap: the earlier offset by default, and the later one on request.
    ZonedDateTime o = ZonedDateTime.of(LocalDateTime.of(2024, 11, 3, 1, 30), ny);
    System.out.println(o + " " + o.withLaterOffsetAtOverlap());

    // A region has rules that change. An offset has one fixed rule.
    System.out.println(ny.getRules().isFixedOffset() + " " + ZoneOffset.ofHours(-5).getRules().isFixedOffset());
  }
}
Output
2024-01-09T07:00-05:00[America/New_York] 2024-07-09T08:00-04:00[America/New_York]
-05:00 -04:00
2024-03-10T03:30-04:00[America/New_York]
2024-11-03T01:30-04:00[America/New_York] 2024-11-03T01:30-05:00[America/New_York]
false true
  • Verdict: stdlib. ZoneId names a region of the IANA database, and its subclass ZoneOffset is a fixed offset. ZoneRules gives the offset at an instant and the transitions, and ZonedDateTime resolves gaps and overlaps with documented rules.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static void show(time_t t) {
    char buf[64];
    strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M%z %Z", localtime(&t));
    puts(buf);
}

int main(void) {
    // A process has one local zone, which the variable TZ sets.
    setenv("TZ", "America/New_York", 1);
    tzset();
    show(1704801600); // 2024-01-09T12:00:00Z
    show(1720526400); // 2024-07-09T12:00:00Z

    // In an overlap, tm_isdst chooses one of the two instants.
    struct tm a = {.tm_year = 124, .tm_mon = 10, .tm_mday = 3, .tm_hour = 1, .tm_min = 30, .tm_isdst = 1};
    struct tm b = a;
    b.tm_isdst = 0;
    time_t ta = mktime(&a);
    time_t tb = mktime(&b);
    printf("%lld\n", (long long)(tb - ta));

    // A POSIX TZ string states the rules directly, with no database.
    setenv("TZ", "EST5EDT,M3.2.0,M11.1.0", 1);
    tzset();
    show(1720526400);
    return 0;
}
Output
2024-01-09T07:00-0500 EST
2024-07-09T08:00-0400 EDT
3600
2024-07-09T08:00-0400 EDT
  • Verdict: stdlib. C has only the local zone of the process. POSIX sets it with the variable TZ, which holds a name of the IANA database or a rule string, and localtime and mktime convert with it. There is no zone value that a program can pass to a function.
using System;
using System.Globalization;

var ny = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
const string f = "yyyy-MM-dd'T'HH:mmzzz";
var winter = new DateTimeOffset(2024, 1, 9, 12, 0, 0, TimeSpan.Zero);
var summer = new DateTimeOffset(2024, 7, 9, 12, 0, 0, TimeSpan.Zero);
Console.WriteLine(TimeZoneInfo.ConvertTime(winter, ny).ToString(f, CultureInfo.InvariantCulture));
Console.WriteLine(TimeZoneInfo.ConvertTime(summer, ny).ToString(f, CultureInfo.InvariantCulture));

// A gap and an overlap.
Console.WriteLine(ny.IsInvalidTime(new DateTime(2024, 3, 10, 2, 30, 0)));
var overlap = new DateTime(2024, 11, 3, 1, 30, 0);
Console.WriteLine(ny.IsAmbiguousTime(overlap));
Console.WriteLine(string.Join(" ", ny.GetAmbiguousTimeOffsets(overlap)));
Output
2024-01-09T07:00-05:00
2024-07-09T08:00-04:00
True
True
-05:00:00 -04:00:00
  • Verdict: stdlib. TimeZoneInfo represents a zone with its adjustment rules, and FindSystemTimeZoneById accepts IANA names on all platforms. IsInvalidTime and IsAmbiguousTime find gaps and overlaps, and DateTimeOffset holds one instant with one offset.
JavaScriptGitHub
// Intl.DateTimeFormat shows an instant in a named zone.
function inZone(date, timeZone) {
  const parts = new Intl.DateTimeFormat("en-CA", {
    timeZone, year: "numeric", month: "2-digit", day: "2-digit",
    hour: "2-digit", minute: "2-digit", hourCycle: "h23", timeZoneName: "shortOffset",
  }).formatToParts(date);
  const p = Object.fromEntries(parts.map((x) => [x.type, x.value]));
  return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute} ${p.timeZoneName}`;
}

// One zone, two offsets: winter and summer.
console.log(inZone(new Date("2024-01-09T12:00:00Z"), "America/New_York"));
console.log(inZone(new Date("2024-07-09T12:00:00Z"), "America/New_York"));

// An overlap: two instants one hour apart show the same local time.
console.log(inZone(new Date("2024-11-03T05:30:00Z"), "America/New_York"));
console.log(inZone(new Date("2024-11-03T06:30:00Z"), "America/New_York"));

// Some offsets are not whole hours.
console.log(inZone(new Date("2024-01-09T12:00:00Z"), "Asia/Kolkata"));
Output
2024-01-09 07:00 GMT-5
2024-07-09 08:00 GMT-4
2024-11-03 01:30 GMT-4
2024-11-03 01:30 GMT-5
2024-01-09 17:30 GMT+5:30
  • Verdict: native. A Date is an instant, and Intl.DateTimeFormat with the option timeZone shows it in any zone of the IANA database. Temporal.ZonedDateTime holds an instant with a zone, and its option disambiguation resolves gaps and overlaps.
package main

import (
	"fmt"
	"time"
)

func main() {
	ny, err := time.LoadLocation("America/New_York")
	if err != nil {
		fmt.Println(err)
		return
	}
	const layout = "2006-01-02T15:04-07:00 MST"
	for _, m := range []time.Month{time.January, time.July} {
		fmt.Println(time.Date(2024, m, 9, 12, 0, 0, 0, time.UTC).In(ny).Format(layout))
	}

	// An overlap: two instants one hour apart have the same local time.
	first := time.Date(2024, 11, 3, 5, 30, 0, 0, time.UTC).In(ny)
	fmt.Println(first.Format(layout), first.Add(time.Hour).Format(layout))

	// A fixed offset with a name is not a zone: its offset never changes.
	est := time.FixedZone("EST", -5*60*60)
	fmt.Println(time.Date(2024, 7, 9, 12, 0, 0, 0, time.UTC).In(est).Format(layout))

	// The name and the offset in seconds of the zone at one instant.
	name, offset := time.Date(2024, 7, 9, 12, 0, 0, 0, ny).Zone()
	fmt.Println(name, offset)
}
Output
2024-01-09T07:00-05:00 EST
2024-07-09T08:00-04:00 EDT
2024-11-03T01:30-04:00 EDT 2024-11-03T01:30-05:00 EST
2024-07-09T07:00-05:00 EST
EDT -14400
  • Verdict: stdlib. time.LoadLocation loads a zone of the IANA database, and time.FixedZone makes a fixed offset. A Time carries its Location, and the method In shows the same instant in another zone.
BashGitHub
# The variable TZ sets the zone for the format %(...)T of printf.
in_zone() (
  export TZ=$1
  printf '%(%Y-%m-%dT%H:%M%z %Z)T\n' "$2"
)

in_zone America/New_York 1704801600
in_zone America/New_York 1720526400
in_zone Asia/Kolkata 1704801600
in_zone UTC 1704801600
Output
2024-01-09T07:00-0500 EST
2024-07-09T08:00-0400 EDT
2024-01-09T17:30+0530 IST
2024-01-09T12:00+0000 UTC
  • Verdict: idiom. Bash has no zone type. The variable TZ sets the zone of a command or a subshell, and the format %(datefmt)T of printf and the external command date use it.
  • Fixed offsets in data. Formats such as RFC 3339 store an offset with each timestamp, such as 2024-07-09T08:00:00-04:00. The offset shows the local time at that instant but not the rules of the zone. The format of RFC 9557 adds a zone name in brackets after the offset. See ISO 8601.
  • POSIX rule strings. A string such as EST5EDT,M3.2.0,M11.1.0 states one fixed rule for daylight saving time, with no history. The C example uses one.
  • The local zone of the system. Each process has a default zone, from the variable TZ or the settings of the system. Functions such as localtime in C and Date getters in JavaScript use it.
  • Calendar arithmetic in a zone. Adding 1 day to a zoned date and time adds a calendar day, which is 23 or 25 hours on the days when the clocks change. See Calendar arithmetic.
  • Converting between zones. The same instant shown in another zone. See Convert between time zones.

Pitfalls

  • An offset stored as a zone. A meeting at 09:00 every Monday in New York has the offset -05:00 in winter and -04:00 in summer. A program that stores only -05:00 moves the meeting by one hour in summer. Store the name America/New_York.
  • Abbreviations as identifiers. The tz project warns that "these abbreviations are ambiguous in practice: e.g., CST means one thing in China and something else in North America, and IST can refer to time in India, Ireland or Israel."5 Parse and store zone names or numeric offsets, and use abbreviations only for display.
  • Future events stored in UTC. The rules of a zone change by law. "For example, if today someone schedules a meeting for 13:00 next October 1, Dublin time, and tomorrow Ireland changes its daylight saving rules, software can mess up after the rule change if it blithely relies on conversions made before the change."5 For a future event in local time, store the local time and the zone name, and compute the instant when it is needed.
  • Days with 23 or 25 hours. On the days when the clocks change, a local day is not 24 hours long. "In the worst case, an entire day may be missing from the local calendar."3 Do not add 86400 seconds to get the next day in a zone.
  • Local times in a gap or an overlap. A user can enter a local time that does not exist or that exists two times. Each library has its own default, as the examples show. Choose the rule on purpose, and test the dates of the changes.
  • A zone column that drops the zone. In PostgreSQL, timestamp with time zone stores an instant, not a zone. A program that needs the zone of the user must store the name in its own column.
  • The zone of the server. Code that uses the local zone of the process gives different results on a laptop and on a server in UTC. Pass the zone explicitly.

Cost

A conversion from an instant to local time is a search in the list of transitions of the zone, followed by an addition. The list is sorted by instant, so a binary search finds the rule. A conversion from local time to an instant also needs the gap and overlap checks. Most libraries cache the parsed rules, so the cost of a load of the zone data is paid once for each zone. The data of the whole database is a few hundred kilobytes in its compiled form, and some platforms do not ship it, so Python can use the package tzdata from PyPI instead: "By default, zoneinfo uses the system's time zone data if available; if no system time zone data is available, the library will fall back to using the first-party tzdata package available on PyPI."9

History

Before the railways, each town kept its own local mean time from the sun. In North America the railroads started standard time zones on Sunday, November 18, 18831. In 1884, Britain helped to gather international consent for global time, and countries moved to zones with offsets from Greenwich. In the United States, Congress made the zones law in the Standard Time Act of March 19, 19181.

Daylight saving time adds a second offset in summer, and governments change its dates often. A POSIX TZ string holds one fixed rule for daylight saving time and no history. The tz database, started by Arthur David Olson, records the changes of each region since 19706. Its "uniform naming convention for entries in the database, such as America/New_York and Europe/Paris, was designed by Paul Eggert."6 Java 8 put ZoneId and ZoneRules into java.time, Python 3.9 added zoneinfo, and C++20 added time_zone and zoned_time11.

References

  1. Time zone, Wikipedia, Introduction; History, Railway time
  2. Class ZoneId, Java SE 25 API, Description
  3. Temporal.ZonedDateTime, MDN Web Docs, Description; Time zones and offsets; Ambiguity and gaps
  4. Package time, Go standard library, type Location; func LoadLocation
  5. Theory and pragmatics of the tz code and data, IANA, Scope of the tz database; Time zone abbreviations; Accuracy of the tz database
  6. tz database, Wikipedia, Introduction; Example zone and rule lines
  7. Class ZonedDateTime, Java SE 25 API, Description
  8. PEP 495, Local Time Disambiguation, Abstract
  9. zoneinfo, IANA time zone support, The Python Standard Library, Introduction
  10. TimeZoneInfo Class, .NET API, Definition; Methods
  11. std::chrono::zoned_time, cppreference.com, Description
  12. Date/Time Types, PostgreSQL Documentation, 8.5.1.3 Time Stamps

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/2M7FMR/text.yaml