Taskcore
Convert between time zones
Also called time zone conversion, convert a local time to another zone, convert to UTC, change the time zone, astimezone, withZoneSameInstant, TimeZoneInfo.ConvertTime, zoned_time, daylight saving time gap, ambiguous local time.
Convert a local date and time in one IANA time zone to the local time of the same instant in another zone. A local time in a gap or an overlap of daylight saving time needs a rule.
- Evidence
- Code in 10 languages
Task
Convert a local date and time in one time zone to the local time of the same instant in another time zone. For example, 12:00 on 2024-07-01 in New York is 16:00 in UTC and 01:00 on the next day in Tokyo.
The contract convert_time_zone(year, month, day, hour, minute, second, from_zone, to_zone) takes the local time as six integers and the two zones as IANA names, such as America/New_York, Asia/Kolkata or UTC. It returns the local time in to_zone as text in the form 2024-07-02T01:00:00+09:00. The offset at the end is the UTC offset of to_zone at that instant, and an offset of zero is +00:00.
The conversion has two steps:
- Find the instant of the local time in
from_zone. This step is hard, because the local clock jumps when daylight saving time starts or stops. - Find the offset of
to_zoneat that instant and add it. This step is easy, because each instant has exactly one offset in each zone.
A local time that a jump skips is in a gap: in New York, 02:30 on 2024-03-10 does not exist. A local time that occurs two times is in an overlap: 01:30 on 2024-11-03 occurs first with the offset -04:00 and then with -05:00. The contract uses this rule:
- A time in a gap moves forward by the length of the gap. 02:30 in the gap of New York is read with the offset before the gap, -05:00, so it is 07:30 UTC, which is 03:30 in New York.
- A time in an overlap uses the earlier of its two instants. 01:30 on 2024-11-03 in New York is 05:30 UTC.
Java uses this rule by default, and so does Python with fold=0. The years are 1970 to 2100. The tz database "organizes time zone and daylight saving time data by partitioning the world into timezones whose clocks all agree about timestamps that occur after the POSIX Epoch (1970-01-01 00:00:00 UTC)", so two names can give different results before 1970.
Solutions
Most solutions find the instant with the same method. Read the local time as if it were UTC, and call that value t. Get the offsets of from_zone at t - 1 day and at t + 1 day. These are the two offsets that can apply to the local time. For each offset, the instant is t - offset. An instant is valid if the zone has that same offset at that instant. Take the earliest valid instant. If no instant is valid, the time is in a gap, and t minus the earlier offset moves it forward by the length of the gap. The method works when a zone changes its offset at most once in a day.
- Python.
datetime(..., tzinfo=ZoneInfo(from_zone)).astimezone(ZoneInfo(to_zone)). The attributefoldis 0 by default, which gives the rule of the contract.isoformat()writes the offset as+HH:MM. - JavaScript. A
Dateis an instant and has no zone.Intl.DateTimeFormatwith the optiontimeZonegives the local date and time of an instant in a zone, and the difference to the UTC fields is the offset. The solution uses the method above to find the instant. The constructor throws aRangeErrorfor an unknown name. - TypeScript. The same code as JavaScript, with types.
- Java.
ZonedDateTime.of(local, ZoneId.of(from_zone)).withZoneSameInstant(ZoneId.of(to_zone)). The patternuuuu-MM-dd'T'HH:mm:ssxxxwrites the offset, with+00:00for zero. - C#. On Linux and macOS,
TimeZoneInfo.FindSystemTimeZoneByIdtakes IANA names.ConvertTimewith aDateTimethrows for a time in a gap, so the solution uses the method above withGetUtcOffset, and then converts aDateTimeOffset, which "cannot represent either an ambiguous time or an invalid time". The formatzzzwrites the offset. - Go.
time.LoadLocationreads the zone.time.Datedoes not promise a rule for a gap or an overlap, so the solution uses the method above. The layout-07:00writes+00:00, and the layoutZ07:00writesZ. - Rust. The standard library has no time zones, so the solution reads the TZif file of the zone from
/usr/share/zoneinfo. A TZif file has a list of transitions and, after them, a footer with a POSIX TZ string such asEST5EDT,M3.2.0,M11.1.0. RFC 9636 says that "Local time for timestamps on or after the last transition is specified by the TZ string in the footer", so the solution uses the rule of that string for dates after the last transition in the file. - C. The C library has only the zone of the process. The solution sets the variable
TZ, callstzsetandlocaltime_r, and restoresTZ. So the function is not safe to call from more than one thread. - C++.
locate_zone(from_zone)->get_info(local)returns alocal_info. For a time in a gap, its memberfirstis "the std::chrono::sys_info that ends just prior to the local_time", and for a time in an overlap it is the earlier one, solocal - first.offsetgives the rule of the contract.std::format("{:%FT%T%Ez}", zoned_time{to_zone, instant})writes the result. - Bash.
TZ=zone date -d @seconds +%zgives the offset of a zone at an instant, and the function uses the method above. The format sequence%:zof GNU date writes "+hh:mm numeric time zone".
With fold=0, Python moves a time in a gap forward and takes the earlier time in an overlap. PEP 495 says that in a gap, "the rules in effect before the transition should be used if fold=0". With fold=1, it uses the rules after the transition:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
ny = ZoneInfo("America/New_York")
for fold in (0, 1):
gap = datetime(2024, 3, 10, 2, 30, fold=fold, tzinfo=ny)
overlap = datetime(2024, 11, 3, 1, 30, fold=fold, tzinfo=ny)
print(fold, gap.astimezone(timezone.utc).time(), overlap.astimezone(timezone.utc).time())
0 07:30:00 05:30:00
1 06:30:00 06:30:00
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
nonexistent-time: 02:30 on 2024-03-10 in New York is in the gap, so it gives 07:30 UTC.ambiguous-timeandambiguous-time-london: 01:30 on the day when daylight saving time stops, in New York and in London. Both give the earlier instant.dst-dates-differ: on 2024-03-20, New York is on daylight saving time and London is not yet, so the difference is 4 hours and not 5.southern-hemisphere: in January, Sydney is on daylight saving time with the offset +11:00.half-hour-offset,45-minute-offsetandhalf-hour-dst: Kolkata has +05:30 and Kathmandu has +05:45. Lord Howe Island changes its offset by 30 minutes, from +10:30 to +11:00.across-the-date-line: Kiritimati has +14:00 and Pago Pago has -11:00, so noon on 2024-01-15 in Kiritimati is 11:00 on 2024-01-14 in Pago Pago.before-skipped-day,skipped-dayandafter-skipped-day: Samoa moved across the date line at the end of 2011, and 2011-12-30 does not exist inPacific/Apia. A time on that day is in a gap of 24 hours, so it gives the same instant as the same time on 2011-12-31.old-dst-rule: in 2006, the United States started daylight saving time in April, so New York had -05:00 on 2006-03-15.posix-sign:Etc/GMT+5is 5 hours behind UTC. See the pitfalls.result-before-epoch: midnight UTC on 1970-01-01 is 19:00 on 1969-12-31 in New York.far-future: the TZif file of a zone can end at 2037, so a date in 2050 needs the rule in the footer of the file.same-zone: a conversion to the same zone keeps the local time.
Pitfalls
- A fixed offset in place of a zone. An offset is right only for some dates.
-05:00is the offset of New York in winter, but not in summer:
This code runs but gives a wrong answer on purpose.
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
fixed = timezone(timedelta(hours=-5))
ny = ZoneInfo("America/New_York")
for month in (1, 7):
a = datetime(2024, month, 15, 12, tzinfo=fixed).astimezone(timezone.utc)
b = datetime(2024, month, 15, 12, tzinfo=ny).astimezone(timezone.utc)
print(month, a.time(), b.time())
1 17:00:00 17:00:00
7 17:00:00 16:00:00
- The sign of
Etc/GMT+5. The namesEtc/GMT+Nuse the sign of POSIX TZ strings, which is the opposite of an ISO 8601 offset. The tz source says that "TZ='Etc/GMT+4' uses the abbreviation "-04" and corresponds to 4 hours behind UT". In a POSIX TZ string, "The offset is positive if the local timezone is west of the Prime Meridian".
This code runs but gives a wrong answer on purpose.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
noon = datetime(2024, 1, 15, 12, tzinfo=timezone.utc)
print(noon.astimezone(ZoneInfo("Etc/GMT+5")).isoformat())
print(noon.astimezone(ZoneInfo("Etc/GMT-5")).isoformat())
2024-01-15T07:00:00-05:00
2024-01-15T17:00:00+05:00
- Go
time.Datein a gap or an overlap. The Go documentation says: "In such cases, the choice of time zone, and therefore the time, is not well-defined. Date returns a time that is correct in one of the two zones involved in the transition, but it does not guarantee which." On this system, New York and London get different rules. In the gap, New York moves 02:30 back to 01:30, and London moves 01:30 forward to 02:30. In the overlap, New York takes the earlier instant and London the later one:
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"time"
)
func main() {
times := []struct {
zone string
month, day, hour int
}{
{"America/New_York", 3, 10, 2},
{"America/New_York", 11, 3, 1},
{"Europe/London", 3, 31, 1},
{"Europe/London", 10, 27, 1},
}
for _, c := range times {
loc, err := time.LoadLocation(c.zone)
if err != nil {
panic(err)
}
t := time.Date(2024, time.Month(c.month), c.day, c.hour, 30, 0, 0, loc)
fmt.Println(c.zone, t.Format("01-02 15:04 -07:00"), t.UTC().Format("15:04"))
}
}
America/New_York 03-10 01:30 -05:00 06:30
America/New_York 11-03 01:30 -04:00 05:30
Europe/London 03-31 02:30 +01:00 01:30
Europe/London 10-27 01:30 +00:00 01:30
Find the offsets yourself, as the solution does, when the rule matters.
- C#
ConvertTimewith aDateTime. The documentation says: "If the value of the dateTime parameter is an ambiguous local time, it is interpreted as a standard time. If the dateTime parameter is an invalid local time, this method throws an ArgumentException." So an overlap gives the later instant, and a gap gives an exception:
This code runs but gives a wrong answer on purpose.
TimeZoneInfo ny = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
var overlap = new DateTime(2024, 11, 3, 1, 30, 0);
Console.WriteLine(TimeZoneInfo.ConvertTime(overlap, ny, TimeZoneInfo.Utc).ToString("HH:mm"));
var gap = new DateTime(2024, 3, 10, 2, 30, 0);
try
{
TimeZoneInfo.ConvertTime(gap, ny, TimeZoneInfo.Utc);
}
catch (ArgumentException e)
{
Console.WriteLine(e.GetType().Name);
}
06:30
ArgumentException
- C++
choose::earliestin a gap.choosecontrols "how ambiguous or nonexistent local times should be resolved", but "For nonexistent local times, these two time points are identical." Both give the instant of the transition, 07:00 UTC, which is 03:00 in New York. The offset inlocal_info::firstmoves the time forward by the length of the gap:
This code runs but gives a wrong answer on purpose.
#include <chrono>
#include <format>
#include <iostream>
int main() {
using namespace std::chrono;
const local_seconds gap = local_days{2024y / March / 10} + 2h + 30min;
const zoned_time<seconds> earliest{"America/New_York", gap, choose::earliest};
const zoned_time<seconds> latest{"America/New_York", gap, choose::latest};
std::cout << std::format("{:%T}", earliest.get_sys_time()) << "\n";
std::cout << std::format("{:%T}", latest.get_sys_time()) << "\n";
const local_info info = locate_zone("America/New_York")->get_info(gap);
std::cout << std::format("{:%T}", sys_seconds{gap.time_since_epoch() - info.first.offset}) << "\n";
}
07:00:00
07:00:00
07:30:00
- The same local time in place of the same instant. Java
withZoneSameLocalkeeps the clock reading and changes the instant. A conversion needswithZoneSameInstant:
This code runs but gives a wrong answer on purpose.
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZonedDateTime noon = ZonedDateTime.of(2024, 7, 1, 12, 0, 0, 0, ZoneId.of("America/New_York"));
System.out.println(noon.withZoneSameLocal(ZoneId.of("Asia/Tokyo")));
System.out.println(noon.withZoneSameInstant(ZoneId.of("Asia/Tokyo")));
}
}
2024-07-01T12:00+09:00[Asia/Tokyo]
2024-07-02T01:00+09:00[Asia/Tokyo]
-
Two libraries can read the same change in different ways. Each library has its own code for the tz data, and a rare change can show a difference. On the test system, with the tz data 2026e, Python, Java, JavaScript and Go give -10:00 for
Pacific/Apiaat 22:00 UTC on 2011-12-29, and +14:00 after the change at 10:00 UTC on 2011-12-30. libstdc++ of GCC 13 and of GCC 15 gives +13:00 from 00:00 UTC on 2011-12-29. The C++ tests check the offset first and skip the cases for Apia when the library gives this result. Test the dates of rare changes in each library that you use. -
An unknown zone name gives UTC with no error. For the variable
TZ, the C library says that if "its value cannot be interpreted using any of the formats specified below, then Coordinated Universal Time (UTC) is used." A misspelled name gives UTC, with part of the name as the abbreviation, anddateexits with status 0:
This code runs but gives a wrong answer on purpose.
TZ=America/New_York date -d @1720000000 '+%H:%M %Z'
TZ=America/New_Yrok date -d @1720000000 '+%H:%M %Z'
echo "status $?"
05:46 EDT
09:46 America
status 0
The C and Bash solutions check that the file of the zone exists. Python, Java, C#, Go and JavaScript throw or return an error for an unknown name.
Related tasks
- Get the current date and time: the current instant in a zone.
- Parse and format a date: text with an offset or a zone name.
- Add days to a date: a day in a zone is not always 24 hours long.
- Get a Unix timestamp: an instant as a number, with no zone.
See Time zone for offsets, gaps and overlaps, and IANA time zone database for the source of the rules.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-between-time-zones/.
from datetime import datetime
from zoneinfo import ZoneInfo
def convert_time_zone(
year: int,
month: int,
day: int,
hour: int,
minute: int,
second: int,
from_zone: str,
to_zone: str,
) -> str:
"""Convert a local date and time in from_zone to local time in to_zone.
The default fold=0 moves a time in a gap forward by the length of the gap
and picks the earlier of two instants in an overlap.
"""
local = datetime(year, month, day, hour, minute, second, tzinfo=ZoneInfo(from_zone))
return local.astimezone(ZoneInfo(to_zone)).isoformat()
test_tzconv.py 56 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-between-time-zones/.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import pytest
from tzconv import convert_time_zone
CASES = [
("new-york-to-utc", (2024, 7, 1, 12, 0, 0, "America/New_York", "UTC"), "2024-07-01T16:00:00+00:00"),
("utc-to-tokyo", (2024, 1, 15, 0, 0, 0, "UTC", "Asia/Tokyo"), "2024-01-15T09:00:00+09:00"),
("london-to-new-york", (2024, 1, 15, 12, 0, 0, "Europe/London", "America/New_York"), "2024-01-15T07:00:00-05:00"),
("date-changes", (2024, 1, 15, 22, 0, 0, "America/Los_Angeles", "Asia/Tokyo"), "2024-01-16T15:00:00+09:00"),
("same-zone", (2024, 3, 10, 12, 0, 0, "America/New_York", "America/New_York"), "2024-03-10T12:00:00-04:00"),
("nonexistent-time", (2024, 3, 10, 2, 30, 0, "America/New_York", "UTC"), "2024-03-10T07:30:00+00:00"),
("ambiguous-time", (2024, 11, 3, 1, 30, 0, "America/New_York", "UTC"), "2024-11-03T05:30:00+00:00"),
("ambiguous-time-london", (2024, 10, 27, 1, 30, 0, "Europe/London", "UTC"), "2024-10-27T00:30:00+00:00"),
("dst-dates-differ", (2024, 3, 20, 12, 0, 0, "America/New_York", "Europe/London"), "2024-03-20T16:00:00+00:00"),
("southern-hemisphere", (2024, 1, 15, 12, 0, 0, "Australia/Sydney", "UTC"), "2024-01-15T01:00:00+00:00"),
("half-hour-offset", (2024, 1, 15, 12, 0, 0, "Asia/Kolkata", "UTC"), "2024-01-15T06:30:00+00:00"),
("45-minute-offset", (2024, 1, 15, 12, 0, 0, "UTC", "Asia/Kathmandu"), "2024-01-15T17:45:00+05:45"),
("half-hour-dst", (2024, 1, 15, 12, 0, 0, "Australia/Lord_Howe", "UTC"), "2024-01-15T01:00:00+00:00"),
("across-the-date-line", (2024, 1, 15, 12, 0, 0, "Pacific/Kiritimati", "Pacific/Pago_Pago"), "2024-01-14T11:00:00-11:00"),
("before-skipped-day", (2011, 12, 29, 12, 0, 0, "Pacific/Apia", "UTC"), "2011-12-29T22:00:00+00:00"),
("skipped-day", (2011, 12, 30, 12, 0, 0, "Pacific/Apia", "UTC"), "2011-12-30T22:00:00+00:00"),
("after-skipped-day", (2011, 12, 31, 12, 0, 0, "Pacific/Apia", "UTC"), "2011-12-30T22:00:00+00:00"),
("old-dst-rule", (2006, 3, 15, 12, 0, 0, "America/New_York", "UTC"), "2006-03-15T17:00:00+00:00"),
("posix-sign", (2024, 1, 15, 12, 0, 0, "UTC", "Etc/GMT+5"), "2024-01-15T07:00:00-05:00"),
("result-before-epoch", (1970, 1, 1, 0, 0, 0, "UTC", "America/New_York"), "1969-12-31T19:00:00-05:00"),
("far-future", (2050, 7, 1, 12, 0, 0, "America/New_York", "UTC"), "2050-07-01T16:00:00+00:00"),
]
@pytest.mark.parametrize("name,args,want", CASES, ids=[c[0] for c in CASES])
def test_cases(name, args, want):
assert convert_time_zone(*args) == want
def test_round_trip():
there = convert_time_zone(2024, 7, 1, 12, 0, 0, "America/New_York", "Asia/Tokyo")
assert there == "2024-07-02T01:00:00+09:00"
assert convert_time_zone(2024, 7, 2, 1, 0, 0, "Asia/Tokyo", "America/New_York") == (
"2024-07-01T12:00:00-04:00"
)
def test_fold_one_picks_the_later_instant():
local = datetime(2024, 11, 3, 1, 30, fold=1, tzinfo=ZoneInfo("America/New_York"))
assert local.astimezone(timezone.utc).hour == 6
def test_unknown_zone():
with pytest.raises(ZoneInfoNotFoundError):
convert_time_zone(2024, 1, 1, 0, 0, 0, "Mars/Olympus", "UTC")
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
#ifndef CONVERT_TIME_ZONE_HPP
#define CONVERT_TIME_ZONE_HPP
#include <chrono>
#include <format>
#include <string>
#include <string_view>
// Returns the instant of a local time in zone. A time in a gap moves forward
// by the length of the gap, and a time in an overlap gives the earlier of its
// two instants. choose::earliest maps a time in a gap to the transition
// itself, so the offset before the gap is used here.
inline std::chrono::sys_seconds local_to_instant(const std::chrono::time_zone* zone,
std::chrono::local_seconds local) {
const std::chrono::local_info info = zone->get_info(local);
// For a unique or nonexistent time, first is the offset before; for an
// ambiguous time, first is the earlier offset.
return std::chrono::sys_seconds{local.time_since_epoch() - info.first.offset};
}
// Returns the local time in to_zone for a local time in from_zone, as
// YYYY-MM-DDTHH:MM:SS+HH:MM. locate_zone throws std::runtime_error for an
// unknown name.
inline std::string convert_time_zone(int year, unsigned month, unsigned day, int hour, int minute,
int second, std::string_view from_zone,
std::string_view to_zone) {
using namespace std::chrono;
const local_seconds local = local_days{std::chrono::year{year} / month / day} + hours{hour} +
minutes{minute} + seconds{second};
const sys_seconds instant = local_to_instant(locate_zone(from_zone), local);
const zoned_time<seconds> there{locate_zone(to_zone), instant};
return std::format("{:%FT%T%Ez}", there);
}
#endif
test_tzconv.cpp 90 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
#include <chrono>
#include <cstdio>
#include <stdexcept>
#include <string>
#include "tzconv.hpp"
namespace {
struct test_case {
const char* name;
int year;
unsigned month, day;
int hour, minute, second;
const char* from_zone;
const char* to_zone;
const char* want;
};
const test_case cases[] = {
{"new-york-to-utc", 2024, 7, 1, 12, 0, 0, "America/New_York", "UTC", "2024-07-01T16:00:00+00:00"},
{"utc-to-tokyo", 2024, 1, 15, 0, 0, 0, "UTC", "Asia/Tokyo", "2024-01-15T09:00:00+09:00"},
{"london-to-new-york", 2024, 1, 15, 12, 0, 0, "Europe/London", "America/New_York", "2024-01-15T07:00:00-05:00"},
{"date-changes", 2024, 1, 15, 22, 0, 0, "America/Los_Angeles", "Asia/Tokyo", "2024-01-16T15:00:00+09:00"},
{"same-zone", 2024, 3, 10, 12, 0, 0, "America/New_York", "America/New_York", "2024-03-10T12:00:00-04:00"},
{"nonexistent-time", 2024, 3, 10, 2, 30, 0, "America/New_York", "UTC", "2024-03-10T07:30:00+00:00"},
{"ambiguous-time", 2024, 11, 3, 1, 30, 0, "America/New_York", "UTC", "2024-11-03T05:30:00+00:00"},
{"ambiguous-time-london", 2024, 10, 27, 1, 30, 0, "Europe/London", "UTC", "2024-10-27T00:30:00+00:00"},
{"dst-dates-differ", 2024, 3, 20, 12, 0, 0, "America/New_York", "Europe/London", "2024-03-20T16:00:00+00:00"},
{"southern-hemisphere", 2024, 1, 15, 12, 0, 0, "Australia/Sydney", "UTC", "2024-01-15T01:00:00+00:00"},
{"half-hour-offset", 2024, 1, 15, 12, 0, 0, "Asia/Kolkata", "UTC", "2024-01-15T06:30:00+00:00"},
{"45-minute-offset", 2024, 1, 15, 12, 0, 0, "UTC", "Asia/Kathmandu", "2024-01-15T17:45:00+05:45"},
{"half-hour-dst", 2024, 1, 15, 12, 0, 0, "Australia/Lord_Howe", "UTC", "2024-01-15T01:00:00+00:00"},
{"across-the-date-line", 2024, 1, 15, 12, 0, 0, "Pacific/Kiritimati", "Pacific/Pago_Pago", "2024-01-14T11:00:00-11:00"},
{"before-skipped-day", 2011, 12, 29, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-29T22:00:00+00:00"},
{"skipped-day", 2011, 12, 30, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-30T22:00:00+00:00"},
{"after-skipped-day", 2011, 12, 31, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-30T22:00:00+00:00"},
{"old-dst-rule", 2006, 3, 15, 12, 0, 0, "America/New_York", "UTC", "2006-03-15T17:00:00+00:00"},
{"posix-sign", 2024, 1, 15, 12, 0, 0, "UTC", "Etc/GMT+5", "2024-01-15T07:00:00-05:00"},
{"result-before-epoch", 1970, 1, 1, 0, 0, 0, "UTC", "America/New_York", "1969-12-31T19:00:00-05:00"},
{"far-future", 2050, 7, 1, 12, 0, 0, "America/New_York", "UTC", "2050-07-01T16:00:00+00:00"},
};
} // namespace
int main() {
using namespace std::chrono;
int failures = 0;
// The tz data has -10:00 in Pacific/Apia until 2011-12-30 10:00 UTC and
// then +14:00. libstdc++ of GCC 13 and GCC 15 gives +13:00 from
// 2011-12-29 00:00 UTC, so the cases for Apia run only with a library
// that reads this change as the data gives it.
const bool apia_ok =
locate_zone("Pacific/Apia")->get_info(sys_days{2011y / December / 29} + 22h).offset == -10h;
if (!apia_ok) {
std::printf("skip the cases for Pacific/Apia\n");
}
for (const test_case& c : cases) {
if (!apia_ok && std::string{c.from_zone} == "Pacific/Apia") {
continue;
}
const std::string got = convert_time_zone(c.year, c.month, c.day, c.hour, c.minute, c.second,
c.from_zone, c.to_zone);
if (got != c.want) {
std::printf("FAIL %s: %s\n", c.name, got.c_str());
++failures;
}
}
// choose::earliest gives the transition itself for a time in a gap.
const local_seconds gap = local_days{2024y / March / 10} + 2h + 30min;
const zoned_time<seconds> at{"America/New_York", gap, choose::earliest};
if (at.get_sys_time() != sys_days{2024y / March / 10} + 7h) {
std::printf("FAIL choose::earliest in a gap\n");
++failures;
}
try {
convert_time_zone(2024, 1, 1, 0, 0, 0, "Mars/Olympus", "UTC");
std::printf("FAIL unknown zone\n");
++failures;
} catch (const std::runtime_error&) {
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
/** Converts a local date and time from one time zone to another. */
public final class TzConv {
private static final DateTimeFormatter FORMAT =
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssxxx");
private TzConv() {}
/**
* Returns the local time in toZone for a local time in fromZone. ZonedDateTime.of moves a time in a
* gap forward by the length of the gap and uses the earlier offset in an overlap.
*/
public static String convertTimeZone(
int year, int month, int day, int hour, int minute, int second, String fromZone, String toZone) {
LocalDateTime local = LocalDateTime.of(year, month, day, hour, minute, second);
ZonedDateTime from = ZonedDateTime.of(local, ZoneId.of(fromZone));
return from.withZoneSameInstant(ZoneId.of(toZone)).format(FORMAT);
}
}
TzConvTest.java 72 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.zone.ZoneRulesException;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class TzConvTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("new-york-to-utc", 2024, 7, 1, 12, 0, 0, "America/New_York", "UTC", "2024-07-01T16:00:00+00:00"),
Arguments.of("utc-to-tokyo", 2024, 1, 15, 0, 0, 0, "UTC", "Asia/Tokyo", "2024-01-15T09:00:00+09:00"),
Arguments.of("london-to-new-york", 2024, 1, 15, 12, 0, 0, "Europe/London", "America/New_York", "2024-01-15T07:00:00-05:00"),
Arguments.of("date-changes", 2024, 1, 15, 22, 0, 0, "America/Los_Angeles", "Asia/Tokyo", "2024-01-16T15:00:00+09:00"),
Arguments.of("same-zone", 2024, 3, 10, 12, 0, 0, "America/New_York", "America/New_York", "2024-03-10T12:00:00-04:00"),
Arguments.of("nonexistent-time", 2024, 3, 10, 2, 30, 0, "America/New_York", "UTC", "2024-03-10T07:30:00+00:00"),
Arguments.of("ambiguous-time", 2024, 11, 3, 1, 30, 0, "America/New_York", "UTC", "2024-11-03T05:30:00+00:00"),
Arguments.of("ambiguous-time-london", 2024, 10, 27, 1, 30, 0, "Europe/London", "UTC", "2024-10-27T00:30:00+00:00"),
Arguments.of("dst-dates-differ", 2024, 3, 20, 12, 0, 0, "America/New_York", "Europe/London", "2024-03-20T16:00:00+00:00"),
Arguments.of("southern-hemisphere", 2024, 1, 15, 12, 0, 0, "Australia/Sydney", "UTC", "2024-01-15T01:00:00+00:00"),
Arguments.of("half-hour-offset", 2024, 1, 15, 12, 0, 0, "Asia/Kolkata", "UTC", "2024-01-15T06:30:00+00:00"),
Arguments.of("45-minute-offset", 2024, 1, 15, 12, 0, 0, "UTC", "Asia/Kathmandu", "2024-01-15T17:45:00+05:45"),
Arguments.of("half-hour-dst", 2024, 1, 15, 12, 0, 0, "Australia/Lord_Howe", "UTC", "2024-01-15T01:00:00+00:00"),
Arguments.of("across-the-date-line", 2024, 1, 15, 12, 0, 0, "Pacific/Kiritimati", "Pacific/Pago_Pago", "2024-01-14T11:00:00-11:00"),
Arguments.of("before-skipped-day", 2011, 12, 29, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-29T22:00:00+00:00"),
Arguments.of("skipped-day", 2011, 12, 30, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-30T22:00:00+00:00"),
Arguments.of("after-skipped-day", 2011, 12, 31, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-30T22:00:00+00:00"),
Arguments.of("old-dst-rule", 2006, 3, 15, 12, 0, 0, "America/New_York", "UTC", "2006-03-15T17:00:00+00:00"),
Arguments.of("posix-sign", 2024, 1, 15, 12, 0, 0, "UTC", "Etc/GMT+5", "2024-01-15T07:00:00-05:00"),
Arguments.of("result-before-epoch", 1970, 1, 1, 0, 0, 0, "UTC", "America/New_York", "1969-12-31T19:00:00-05:00"),
Arguments.of("far-future", 2050, 7, 1, 12, 0, 0, "America/New_York", "UTC", "2050-07-01T16:00:00+00:00"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void convert(
String name,
int year,
int month,
int day,
int hour,
int minute,
int second,
String fromZone,
String toZone,
String want) {
assertEquals(want, TzConv.convertTimeZone(year, month, day, hour, minute, second, fromZone, toZone));
}
@Test
void laterOffsetAtOverlap() {
ZonedDateTime earlier =
ZonedDateTime.of(LocalDateTime.of(2024, 11, 3, 1, 30), ZoneId.of("America/New_York"));
assertEquals(ZoneOffset.ofHours(-4), earlier.getOffset());
assertEquals(ZoneOffset.ofHours(-5), earlier.withLaterOffsetAtOverlap().getOffset());
}
@Test
void unknownZone() {
assertThrows(ZoneRulesException.class, () -> TzConv.convertTimeZone(2024, 1, 1, 0, 0, 0, "Mars/Olympus", "UTC"));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
#define _POSIX_C_SOURCE 200809L
#include "tzconv.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
// Days from 1970-01-01 to a date of the proleptic Gregorian calendar.
static long long days_from_civil(long long y, int m, int d) {
y -= m <= 2;
const long long era = (y >= 0 ? y : y - 399) / 400;
const long long yoe = y - era * 400;
const long long doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
const long long doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + doe - 719468;
}
static long long as_utc(const struct tm *tm) {
return days_from_civil(tm->tm_year + 1900LL, tm->tm_mon + 1, tm->tm_mday) * 86400 +
tm->tm_hour * 3600LL + tm->tm_min * 60LL + tm->tm_sec;
}
// localtime_r with an unknown TZ value uses UTC and reports no error, so
// the zone file is checked first.
static int zone_exists(const char *zone) {
const char *dir = getenv("TZDIR");
char path[512];
if (strstr(zone, "..") != NULL || zone[0] == '/') {
return 0;
}
snprintf(path, sizeof path, "%s/%s", dir != NULL ? dir : "/usr/share/zoneinfo", zone);
return access(path, R_OK) == 0;
}
// The UTC offset, in seconds, of the zone in TZ at the instant t.
static long long offset_at(long long t) {
const time_t tt = (time_t)t;
struct tm tm;
localtime_r(&tt, &tm);
return as_utc(&tm) - t;
}
static void set_zone(const char *zone) {
if (zone != NULL) {
setenv("TZ", zone, 1);
} else {
unsetenv("TZ");
}
tzset();
}
int convert_time_zone(int year, int month, int day, int hour, int minute,
int second, const char *from_zone, const char *to_zone,
char out[TZCONV_SIZE]) {
if (!zone_exists(from_zone) || !zone_exists(to_zone)) {
return -1;
}
const char *old = getenv("TZ");
char *saved = old != NULL ? strdup(old) : NULL;
set_zone(from_zone);
const long long t = days_from_civil(year, month, day) * 86400 + hour * 3600LL +
minute * 60LL + second;
const long long offsets[2] = {offset_at(t - 86400), offset_at(t + 86400)};
long long instant = t - offsets[0]; // a time in a gap
int found = 0;
for (int i = 0; i < 2; i++) {
const long long u = t - offsets[i];
if (offset_at(u) == offsets[i] && (!found || u < instant)) {
instant = u;
found = 1;
}
}
set_zone(to_zone);
const long long offset = offset_at(instant);
const time_t tt = (time_t)instant;
struct tm tm;
localtime_r(&tt, &tm);
set_zone(saved);
free(saved);
// The buffer has room for any int values, so the compiler can see that
// snprintf does not truncate. For the years 1970 to 2100 the text has
// TZCONV_SIZE - 1 characters.
char text[128];
const long long a = offset < 0 ? -offset : offset;
const int n = snprintf(text, sizeof text, "%04d-%02d-%02dT%02d:%02d:%02d%c%02lld:%02lld",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min,
tm.tm_sec, offset < 0 ? '-' : '+', a / 3600, a % 3600 / 60);
if (n != TZCONV_SIZE - 1) {
return -1;
}
memcpy(out, text, TZCONV_SIZE);
return 0;
}
tzconv.h 18 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
#ifndef CONVERT_TIME_ZONE_H
#define CONVERT_TIME_ZONE_H
// The size of "YYYY-MM-DDTHH:MM:SS+HH:MM" with its terminating null.
#define TZCONV_SIZE 26
// Writes the local time in to_zone for a local time in from_zone to out.
// Returns 0, or -1 if a zone has no file in the tz database or the result
// does not fit the form. The function changes the TZ environment variable
// and restores it, so it is not safe to call from more than one thread.
int convert_time_zone(int year, int month, int day, int hour, int minute,
int second, const char *from_zone, const char *to_zone,
char out[TZCONV_SIZE]);
#endif
test_tzconv.c 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
#include "tzconv.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test_case {
const char *name;
int year, month, day, hour, minute, second;
const char *from_zone;
const char *to_zone;
const char *want;
};
static const struct test_case cases[] = {
{"new-york-to-utc", 2024, 7, 1, 12, 0, 0, "America/New_York", "UTC", "2024-07-01T16:00:00+00:00"},
{"utc-to-tokyo", 2024, 1, 15, 0, 0, 0, "UTC", "Asia/Tokyo", "2024-01-15T09:00:00+09:00"},
{"london-to-new-york", 2024, 1, 15, 12, 0, 0, "Europe/London", "America/New_York", "2024-01-15T07:00:00-05:00"},
{"date-changes", 2024, 1, 15, 22, 0, 0, "America/Los_Angeles", "Asia/Tokyo", "2024-01-16T15:00:00+09:00"},
{"same-zone", 2024, 3, 10, 12, 0, 0, "America/New_York", "America/New_York", "2024-03-10T12:00:00-04:00"},
{"nonexistent-time", 2024, 3, 10, 2, 30, 0, "America/New_York", "UTC", "2024-03-10T07:30:00+00:00"},
{"ambiguous-time", 2024, 11, 3, 1, 30, 0, "America/New_York", "UTC", "2024-11-03T05:30:00+00:00"},
{"ambiguous-time-london", 2024, 10, 27, 1, 30, 0, "Europe/London", "UTC", "2024-10-27T00:30:00+00:00"},
{"dst-dates-differ", 2024, 3, 20, 12, 0, 0, "America/New_York", "Europe/London", "2024-03-20T16:00:00+00:00"},
{"southern-hemisphere", 2024, 1, 15, 12, 0, 0, "Australia/Sydney", "UTC", "2024-01-15T01:00:00+00:00"},
{"half-hour-offset", 2024, 1, 15, 12, 0, 0, "Asia/Kolkata", "UTC", "2024-01-15T06:30:00+00:00"},
{"45-minute-offset", 2024, 1, 15, 12, 0, 0, "UTC", "Asia/Kathmandu", "2024-01-15T17:45:00+05:45"},
{"half-hour-dst", 2024, 1, 15, 12, 0, 0, "Australia/Lord_Howe", "UTC", "2024-01-15T01:00:00+00:00"},
{"across-the-date-line", 2024, 1, 15, 12, 0, 0, "Pacific/Kiritimati", "Pacific/Pago_Pago", "2024-01-14T11:00:00-11:00"},
{"before-skipped-day", 2011, 12, 29, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-29T22:00:00+00:00"},
{"skipped-day", 2011, 12, 30, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-30T22:00:00+00:00"},
{"after-skipped-day", 2011, 12, 31, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-30T22:00:00+00:00"},
{"old-dst-rule", 2006, 3, 15, 12, 0, 0, "America/New_York", "UTC", "2006-03-15T17:00:00+00:00"},
{"posix-sign", 2024, 1, 15, 12, 0, 0, "UTC", "Etc/GMT+5", "2024-01-15T07:00:00-05:00"},
{"result-before-epoch", 1970, 1, 1, 0, 0, 0, "UTC", "America/New_York", "1969-12-31T19:00:00-05:00"},
{"far-future", 2050, 7, 1, 12, 0, 0, "America/New_York", "UTC", "2050-07-01T16:00:00+00:00"},
};
int main(void) {
int failures = 0;
char out[TZCONV_SIZE];
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
if (convert_time_zone(c->year, c->month, c->day, c->hour, c->minute, c->second,
c->from_zone, c->to_zone, out) != 0 ||
strcmp(out, c->want) != 0) {
printf("FAIL %s: %s\n", c->name, out);
failures++;
}
}
if (convert_time_zone(2024, 1, 1, 0, 0, 0, "Mars/Olympus", "UTC", out) != -1) {
printf("FAIL unknown zone\n");
failures++;
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
using System;
using System.Globalization;
/// <summary>Converts a local date and time from one time zone to another.</summary>
public static class TzConv
{
/// <summary>
/// Returns the instant of a local time in zone. A time in a gap moves forward by the length of the
/// gap, and a time in an overlap gives the earlier of its two instants. TimeZoneInfo.ConvertTime
/// throws for a time in a gap, so the offsets are checked here.
/// </summary>
public static DateTimeOffset LocalToInstant(DateTime local, TimeZoneInfo zone)
{
var t = DateTime.SpecifyKind(local, DateTimeKind.Utc);
TimeSpan before = zone.GetUtcOffset(t.AddDays(-1));
TimeSpan after = zone.GetUtcOffset(t.AddDays(1));
DateTime? instant = null;
foreach (TimeSpan offset in new[] { before, after })
{
DateTime u = t - offset;
if (zone.GetUtcOffset(u) == offset && (instant is null || u < instant))
{
instant = u;
}
}
return new DateTimeOffset(instant ?? t - before, TimeSpan.Zero);
}
public static string ConvertTimeZone(
int year, int month, int day, int hour, int minute, int second, string fromZone, string toZone)
{
TimeZoneInfo from = TimeZoneInfo.FindSystemTimeZoneById(fromZone);
TimeZoneInfo to = TimeZoneInfo.FindSystemTimeZoneById(toZone);
DateTimeOffset instant = LocalToInstant(new DateTime(year, month, day, hour, minute, second), from);
return TimeZoneInfo.ConvertTime(instant, to)
.ToString("yyyy-MM-dd'T'HH:mm:sszzz", CultureInfo.InvariantCulture);
}
}
TzConvTests.cs 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
using System;
using Xunit;
public sealed class TzConvTests
{
public static TheoryData<string, int, int, int, int, int, int, string, string, string> Cases => new()
{
{ "new-york-to-utc", 2024, 7, 1, 12, 0, 0, "America/New_York", "UTC", "2024-07-01T16:00:00+00:00" },
{ "utc-to-tokyo", 2024, 1, 15, 0, 0, 0, "UTC", "Asia/Tokyo", "2024-01-15T09:00:00+09:00" },
{ "london-to-new-york", 2024, 1, 15, 12, 0, 0, "Europe/London", "America/New_York", "2024-01-15T07:00:00-05:00" },
{ "date-changes", 2024, 1, 15, 22, 0, 0, "America/Los_Angeles", "Asia/Tokyo", "2024-01-16T15:00:00+09:00" },
{ "same-zone", 2024, 3, 10, 12, 0, 0, "America/New_York", "America/New_York", "2024-03-10T12:00:00-04:00" },
{ "nonexistent-time", 2024, 3, 10, 2, 30, 0, "America/New_York", "UTC", "2024-03-10T07:30:00+00:00" },
{ "ambiguous-time", 2024, 11, 3, 1, 30, 0, "America/New_York", "UTC", "2024-11-03T05:30:00+00:00" },
{ "ambiguous-time-london", 2024, 10, 27, 1, 30, 0, "Europe/London", "UTC", "2024-10-27T00:30:00+00:00" },
{ "dst-dates-differ", 2024, 3, 20, 12, 0, 0, "America/New_York", "Europe/London", "2024-03-20T16:00:00+00:00" },
{ "southern-hemisphere", 2024, 1, 15, 12, 0, 0, "Australia/Sydney", "UTC", "2024-01-15T01:00:00+00:00" },
{ "half-hour-offset", 2024, 1, 15, 12, 0, 0, "Asia/Kolkata", "UTC", "2024-01-15T06:30:00+00:00" },
{ "45-minute-offset", 2024, 1, 15, 12, 0, 0, "UTC", "Asia/Kathmandu", "2024-01-15T17:45:00+05:45" },
{ "half-hour-dst", 2024, 1, 15, 12, 0, 0, "Australia/Lord_Howe", "UTC", "2024-01-15T01:00:00+00:00" },
{ "across-the-date-line", 2024, 1, 15, 12, 0, 0, "Pacific/Kiritimati", "Pacific/Pago_Pago", "2024-01-14T11:00:00-11:00" },
{ "before-skipped-day", 2011, 12, 29, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-29T22:00:00+00:00" },
{ "skipped-day", 2011, 12, 30, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-30T22:00:00+00:00" },
{ "after-skipped-day", 2011, 12, 31, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-30T22:00:00+00:00" },
{ "old-dst-rule", 2006, 3, 15, 12, 0, 0, "America/New_York", "UTC", "2006-03-15T17:00:00+00:00" },
{ "posix-sign", 2024, 1, 15, 12, 0, 0, "UTC", "Etc/GMT+5", "2024-01-15T07:00:00-05:00" },
{ "result-before-epoch", 1970, 1, 1, 0, 0, 0, "UTC", "America/New_York", "1969-12-31T19:00:00-05:00" },
{ "far-future", 2050, 7, 1, 12, 0, 0, "America/New_York", "UTC", "2050-07-01T16:00:00+00:00" },
};
[Theory]
[MemberData(nameof(Cases))]
public void Convert(
string name, int year, int month, int day, int hour, int minute, int second,
string fromZone, string toZone, string want)
{
Assert.NotNull(name);
Assert.Equal(want, TzConv.ConvertTimeZone(year, month, day, hour, minute, second, fromZone, toZone));
}
[Fact]
public void ConvertTimeThrowsInAGap()
{
TimeZoneInfo ny = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
var gap = new DateTime(2024, 3, 10, 2, 30, 0);
Assert.True(ny.IsInvalidTime(gap));
Assert.Throws<ArgumentException>(() => TimeZoneInfo.ConvertTime(gap, ny, TimeZoneInfo.Utc));
}
[Fact]
public void UnknownZone()
{
Assert.Throws<TimeZoneNotFoundException>(() => TzConv.ConvertTimeZone(2024, 1, 1, 0, 0, 0, "Mars/Olympus", "UTC"));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
const formatters = new Map();
function formatter(zone) {
let f = formatters.get(zone);
if (f === undefined) {
// The constructor throws a RangeError for an unknown zone name.
f = new Intl.DateTimeFormat("en-US", {
timeZone: zone,
hourCycle: "h23",
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
});
formatters.set(zone, f);
}
return f;
}
// Returns the UTC offset of zone, in seconds, at t seconds after the epoch.
export function offsetSeconds(zone, t) {
const p = {};
for (const part of formatter(zone).formatToParts(new Date(t * 1000))) {
p[part.type] = Number(part.value);
}
const local = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) / 1000;
return local - t;
}
// Returns the instant, in seconds after the epoch, of a local time in zone.
// A time in a gap moves forward by the length of the gap, and a time in an
// overlap gives the earlier of its two instants.
export function localToInstant(year, month, day, hour, minute, second, zone) {
const t = Date.UTC(year, month - 1, day, hour, minute, second) / 1000;
const before = offsetSeconds(zone, t - 86400);
const after = offsetSeconds(zone, t + 86400);
let instant = null;
for (const offset of [before, after]) {
const u = t - offset;
if (offsetSeconds(zone, u) === offset && (instant === null || u < instant)) {
instant = u;
}
}
return instant === null ? t - before : instant;
}
function formatOffset(offset) {
const sign = offset < 0 ? "-" : "+";
const abs = Math.abs(offset);
const hh = String(Math.floor(abs / 3600)).padStart(2, "0");
const mm = String(Math.floor((abs % 3600) / 60)).padStart(2, "0");
return `${sign}${hh}:${mm}`;
}
export function convertTimeZone(year, month, day, hour, minute, second, fromZone, toZone) {
const instant = localToInstant(year, month, day, hour, minute, second, fromZone);
const offset = offsetSeconds(toZone, instant);
const local = new Date((instant + offset) * 1000).toISOString().slice(0, 19);
return local + formatOffset(offset);
}
tzconv.test.js 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { convertTimeZone, offsetSeconds } from "./tzconv.js";
const cases = [
["new-york-to-utc", [2024, 7, 1, 12, 0, 0, "America/New_York", "UTC"], "2024-07-01T16:00:00+00:00"],
["utc-to-tokyo", [2024, 1, 15, 0, 0, 0, "UTC", "Asia/Tokyo"], "2024-01-15T09:00:00+09:00"],
["london-to-new-york", [2024, 1, 15, 12, 0, 0, "Europe/London", "America/New_York"], "2024-01-15T07:00:00-05:00"],
["date-changes", [2024, 1, 15, 22, 0, 0, "America/Los_Angeles", "Asia/Tokyo"], "2024-01-16T15:00:00+09:00"],
["same-zone", [2024, 3, 10, 12, 0, 0, "America/New_York", "America/New_York"], "2024-03-10T12:00:00-04:00"],
["nonexistent-time", [2024, 3, 10, 2, 30, 0, "America/New_York", "UTC"], "2024-03-10T07:30:00+00:00"],
["ambiguous-time", [2024, 11, 3, 1, 30, 0, "America/New_York", "UTC"], "2024-11-03T05:30:00+00:00"],
["ambiguous-time-london", [2024, 10, 27, 1, 30, 0, "Europe/London", "UTC"], "2024-10-27T00:30:00+00:00"],
["dst-dates-differ", [2024, 3, 20, 12, 0, 0, "America/New_York", "Europe/London"], "2024-03-20T16:00:00+00:00"],
["southern-hemisphere", [2024, 1, 15, 12, 0, 0, "Australia/Sydney", "UTC"], "2024-01-15T01:00:00+00:00"],
["half-hour-offset", [2024, 1, 15, 12, 0, 0, "Asia/Kolkata", "UTC"], "2024-01-15T06:30:00+00:00"],
["45-minute-offset", [2024, 1, 15, 12, 0, 0, "UTC", "Asia/Kathmandu"], "2024-01-15T17:45:00+05:45"],
["half-hour-dst", [2024, 1, 15, 12, 0, 0, "Australia/Lord_Howe", "UTC"], "2024-01-15T01:00:00+00:00"],
["across-the-date-line", [2024, 1, 15, 12, 0, 0, "Pacific/Kiritimati", "Pacific/Pago_Pago"], "2024-01-14T11:00:00-11:00"],
["before-skipped-day", [2011, 12, 29, 12, 0, 0, "Pacific/Apia", "UTC"], "2011-12-29T22:00:00+00:00"],
["skipped-day", [2011, 12, 30, 12, 0, 0, "Pacific/Apia", "UTC"], "2011-12-30T22:00:00+00:00"],
["after-skipped-day", [2011, 12, 31, 12, 0, 0, "Pacific/Apia", "UTC"], "2011-12-30T22:00:00+00:00"],
["old-dst-rule", [2006, 3, 15, 12, 0, 0, "America/New_York", "UTC"], "2006-03-15T17:00:00+00:00"],
["posix-sign", [2024, 1, 15, 12, 0, 0, "UTC", "Etc/GMT+5"], "2024-01-15T07:00:00-05:00"],
["result-before-epoch", [1970, 1, 1, 0, 0, 0, "UTC", "America/New_York"], "1969-12-31T19:00:00-05:00"],
["far-future", [2050, 7, 1, 12, 0, 0, "America/New_York", "UTC"], "2050-07-01T16:00:00+00:00"],
];
for (const [name, args, want] of cases) {
test(name, () => {
assert.equal(convertTimeZone(...args), want);
});
}
test("offset of a 45-minute zone", () => {
assert.equal(offsetSeconds("Asia/Kathmandu", 0), 19800);
assert.equal(offsetSeconds("Asia/Kathmandu", Date.UTC(2024, 0, 1) / 1000), 20700);
});
test("unknown zone", () => {
assert.throws(() => convertTimeZone(2024, 1, 1, 0, 0, 0, "Mars/Olympus", "UTC"), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
const formatters = new Map<string, Intl.DateTimeFormat>();
function formatter(zone: string): Intl.DateTimeFormat {
let f = formatters.get(zone);
if (f === undefined) {
// The constructor throws a RangeError for an unknown zone name.
f = new Intl.DateTimeFormat("en-US", {
timeZone: zone,
hourCycle: "h23",
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
});
formatters.set(zone, f);
}
return f;
}
// Returns the UTC offset of zone, in seconds, at t seconds after the epoch.
export function offsetSeconds(zone: string, t: number): number {
const p = { year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0 };
for (const part of formatter(zone).formatToParts(new Date(t * 1000))) {
if (part.type in p) {
p[part.type as keyof typeof p] = Number(part.value);
}
}
const local = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) / 1000;
return local - t;
}
// Returns the instant, in seconds after the epoch, of a local time in zone.
// A time in a gap moves forward by the length of the gap, and a time in an
// overlap gives the earlier of its two instants.
export function localToInstant(
year: number,
month: number,
day: number,
hour: number,
minute: number,
second: number,
zone: string,
): number {
const t = Date.UTC(year, month - 1, day, hour, minute, second) / 1000;
const before = offsetSeconds(zone, t - 86400);
const after = offsetSeconds(zone, t + 86400);
let instant: number | null = null;
for (const offset of [before, after]) {
const u = t - offset;
if (offsetSeconds(zone, u) === offset && (instant === null || u < instant)) {
instant = u;
}
}
return instant === null ? t - before : instant;
}
function formatOffset(offset: number): string {
const sign = offset < 0 ? "-" : "+";
const abs = Math.abs(offset);
const hh = String(Math.floor(abs / 3600)).padStart(2, "0");
const mm = String(Math.floor((abs % 3600) / 60)).padStart(2, "0");
return `${sign}${hh}:${mm}`;
}
export function convertTimeZone(
year: number,
month: number,
day: number,
hour: number,
minute: number,
second: number,
fromZone: string,
toZone: string,
): string {
const instant = localToInstant(year, month, day, hour, minute, second, fromZone);
const offset = offsetSeconds(toZone, instant);
const local = new Date((instant + offset) * 1000).toISOString().slice(0, 19);
return local + formatOffset(offset);
}
tzconv.test.ts 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { convertTimeZone, offsetSeconds } from "./tzconv.ts";
const cases: [string, [number, number, number, number, number, number, string, string], string][] = [
["new-york-to-utc", [2024, 7, 1, 12, 0, 0, "America/New_York", "UTC"], "2024-07-01T16:00:00+00:00"],
["utc-to-tokyo", [2024, 1, 15, 0, 0, 0, "UTC", "Asia/Tokyo"], "2024-01-15T09:00:00+09:00"],
["london-to-new-york", [2024, 1, 15, 12, 0, 0, "Europe/London", "America/New_York"], "2024-01-15T07:00:00-05:00"],
["date-changes", [2024, 1, 15, 22, 0, 0, "America/Los_Angeles", "Asia/Tokyo"], "2024-01-16T15:00:00+09:00"],
["same-zone", [2024, 3, 10, 12, 0, 0, "America/New_York", "America/New_York"], "2024-03-10T12:00:00-04:00"],
["nonexistent-time", [2024, 3, 10, 2, 30, 0, "America/New_York", "UTC"], "2024-03-10T07:30:00+00:00"],
["ambiguous-time", [2024, 11, 3, 1, 30, 0, "America/New_York", "UTC"], "2024-11-03T05:30:00+00:00"],
["ambiguous-time-london", [2024, 10, 27, 1, 30, 0, "Europe/London", "UTC"], "2024-10-27T00:30:00+00:00"],
["dst-dates-differ", [2024, 3, 20, 12, 0, 0, "America/New_York", "Europe/London"], "2024-03-20T16:00:00+00:00"],
["southern-hemisphere", [2024, 1, 15, 12, 0, 0, "Australia/Sydney", "UTC"], "2024-01-15T01:00:00+00:00"],
["half-hour-offset", [2024, 1, 15, 12, 0, 0, "Asia/Kolkata", "UTC"], "2024-01-15T06:30:00+00:00"],
["45-minute-offset", [2024, 1, 15, 12, 0, 0, "UTC", "Asia/Kathmandu"], "2024-01-15T17:45:00+05:45"],
["half-hour-dst", [2024, 1, 15, 12, 0, 0, "Australia/Lord_Howe", "UTC"], "2024-01-15T01:00:00+00:00"],
["across-the-date-line", [2024, 1, 15, 12, 0, 0, "Pacific/Kiritimati", "Pacific/Pago_Pago"], "2024-01-14T11:00:00-11:00"],
["before-skipped-day", [2011, 12, 29, 12, 0, 0, "Pacific/Apia", "UTC"], "2011-12-29T22:00:00+00:00"],
["skipped-day", [2011, 12, 30, 12, 0, 0, "Pacific/Apia", "UTC"], "2011-12-30T22:00:00+00:00"],
["after-skipped-day", [2011, 12, 31, 12, 0, 0, "Pacific/Apia", "UTC"], "2011-12-30T22:00:00+00:00"],
["old-dst-rule", [2006, 3, 15, 12, 0, 0, "America/New_York", "UTC"], "2006-03-15T17:00:00+00:00"],
["posix-sign", [2024, 1, 15, 12, 0, 0, "UTC", "Etc/GMT+5"], "2024-01-15T07:00:00-05:00"],
["result-before-epoch", [1970, 1, 1, 0, 0, 0, "UTC", "America/New_York"], "1969-12-31T19:00:00-05:00"],
["far-future", [2050, 7, 1, 12, 0, 0, "America/New_York", "UTC"], "2050-07-01T16:00:00+00:00"],
];
for (const [name, args, want] of cases) {
test(name, () => {
assert.equal(convertTimeZone(...args), want);
});
}
test("offset of a 45-minute zone", () => {
assert.equal(offsetSeconds("Asia/Kathmandu", 0), 19800);
assert.equal(offsetSeconds("Asia/Kathmandu", Date.UTC(2024, 0, 1) / 1000), 20700);
});
test("unknown zone", () => {
assert.throws(() => convertTimeZone(2024, 1, 1, 0, 0, 0, "Mars/Olympus", "UTC"), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
// Package tzconv converts a local date and time from one time zone to another.
package tzconv
import "time"
// offsetAt returns the UTC offset of loc, in seconds, at the instant t.
func offsetAt(loc *time.Location, t int64) int64 {
_, offset := time.Unix(t, 0).In(loc).Zone()
return int64(offset)
}
// LocalToInstant returns the instant of a local time in loc. A time in a gap
// moves forward by the length of the gap, and a time in an overlap gives the
// earlier of its two instants. time.Date does not promise either choice.
func LocalToInstant(year, month, day, hour, minute, second int, loc *time.Location) time.Time {
t := time.Date(year, time.Month(month), day, hour, minute, second, 0, time.UTC).Unix()
before := offsetAt(loc, t-86400)
after := offsetAt(loc, t+86400)
found := false
var instant int64
for _, offset := range []int64{before, after} {
u := t - offset
if offsetAt(loc, u) == offset && (!found || u < instant) {
instant, found = u, true
}
}
if !found {
instant = t - before
}
return time.Unix(instant, 0)
}
// ConvertTimeZone returns the local time in toZone for a local time in
// fromZone, as YYYY-MM-DDTHH:MM:SS+HH:MM.
func ConvertTimeZone(year, month, day, hour, minute, second int, fromZone, toZone string) (string, error) {
from, err := time.LoadLocation(fromZone)
if err != nil {
return "", err
}
to, err := time.LoadLocation(toZone)
if err != nil {
return "", err
}
instant := LocalToInstant(year, month, day, hour, minute, second, from)
return instant.In(to).Format("2006-01-02T15:04:05-07:00"), nil
}
tzconv_test.go 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
package tzconv
import "testing"
var cases = []struct {
name string
year, month, day, hour, minute, second int
fromZone, toZone string
want string
}{
{"new-york-to-utc", 2024, 7, 1, 12, 0, 0, "America/New_York", "UTC", "2024-07-01T16:00:00+00:00"},
{"utc-to-tokyo", 2024, 1, 15, 0, 0, 0, "UTC", "Asia/Tokyo", "2024-01-15T09:00:00+09:00"},
{"london-to-new-york", 2024, 1, 15, 12, 0, 0, "Europe/London", "America/New_York", "2024-01-15T07:00:00-05:00"},
{"date-changes", 2024, 1, 15, 22, 0, 0, "America/Los_Angeles", "Asia/Tokyo", "2024-01-16T15:00:00+09:00"},
{"same-zone", 2024, 3, 10, 12, 0, 0, "America/New_York", "America/New_York", "2024-03-10T12:00:00-04:00"},
{"nonexistent-time", 2024, 3, 10, 2, 30, 0, "America/New_York", "UTC", "2024-03-10T07:30:00+00:00"},
{"ambiguous-time", 2024, 11, 3, 1, 30, 0, "America/New_York", "UTC", "2024-11-03T05:30:00+00:00"},
{"ambiguous-time-london", 2024, 10, 27, 1, 30, 0, "Europe/London", "UTC", "2024-10-27T00:30:00+00:00"},
{"dst-dates-differ", 2024, 3, 20, 12, 0, 0, "America/New_York", "Europe/London", "2024-03-20T16:00:00+00:00"},
{"southern-hemisphere", 2024, 1, 15, 12, 0, 0, "Australia/Sydney", "UTC", "2024-01-15T01:00:00+00:00"},
{"half-hour-offset", 2024, 1, 15, 12, 0, 0, "Asia/Kolkata", "UTC", "2024-01-15T06:30:00+00:00"},
{"45-minute-offset", 2024, 1, 15, 12, 0, 0, "UTC", "Asia/Kathmandu", "2024-01-15T17:45:00+05:45"},
{"half-hour-dst", 2024, 1, 15, 12, 0, 0, "Australia/Lord_Howe", "UTC", "2024-01-15T01:00:00+00:00"},
{"across-the-date-line", 2024, 1, 15, 12, 0, 0, "Pacific/Kiritimati", "Pacific/Pago_Pago", "2024-01-14T11:00:00-11:00"},
{"before-skipped-day", 2011, 12, 29, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-29T22:00:00+00:00"},
{"skipped-day", 2011, 12, 30, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-30T22:00:00+00:00"},
{"after-skipped-day", 2011, 12, 31, 12, 0, 0, "Pacific/Apia", "UTC", "2011-12-30T22:00:00+00:00"},
{"old-dst-rule", 2006, 3, 15, 12, 0, 0, "America/New_York", "UTC", "2006-03-15T17:00:00+00:00"},
{"posix-sign", 2024, 1, 15, 12, 0, 0, "UTC", "Etc/GMT+5", "2024-01-15T07:00:00-05:00"},
{"result-before-epoch", 1970, 1, 1, 0, 0, 0, "UTC", "America/New_York", "1969-12-31T19:00:00-05:00"},
{"far-future", 2050, 7, 1, 12, 0, 0, "America/New_York", "UTC", "2050-07-01T16:00:00+00:00"},
}
func TestConvertTimeZone(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := ConvertTimeZone(c.year, c.month, c.day, c.hour, c.minute, c.second, c.fromZone, c.toZone)
if err != nil {
t.Fatal(err)
}
if got != c.want {
t.Errorf("got %s, want %s", got, c.want)
}
})
}
}
func TestUnknownZone(t *testing.T) {
if _, err := ConvertTimeZone(2024, 1, 1, 0, 0, 0, "Mars/Olympus", "UTC"); err == nil {
t.Fatal("no error for an unknown zone")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
//! Converts a local date and time from one time zone to another. The standard
//! library has no time zones, so this module reads the TZif files of the system
//! tz database (RFC 9636), including the TZ string footer that gives the rules
//! after the last transition in the file.
use std::fs;
/// Days from 1970-01-01 to a date of the proleptic Gregorian calendar.
fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = i64::from((m + 9) % 12);
let doy = (153 * mp + 2) / 5 + i64::from(d) - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
/// The date of a day number from days_from_civil.
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(yoe + era * 400 + i64::from(m <= 2), m, d)
}
fn is_leap(y: i64) -> bool {
y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)
}
/// A day in a POSIX TZ string rule.
#[derive(Debug, Clone, Copy)]
enum Day {
/// Jn: day 1 to 365, where February 29 is never counted.
Julian(i64),
/// n: day 0 to 365, where February 29 is counted.
Zero(i64),
/// Mm.w.d: day d (0 is Sunday) of week w (5 is the last) of month m.
MonthWeek(u32, i64, i64),
}
impl Day {
fn days(self, y: i64) -> i64 {
match self {
Day::Julian(n) => days_from_civil(y, 1, 1) + n - 1 + i64::from(is_leap(y) && n >= 60),
Day::Zero(n) => days_from_civil(y, 1, 1) + n,
Day::MonthWeek(m, w, d) => {
let first = days_from_civil(y, m, 1);
let next = if m == 12 {
days_from_civil(y + 1, 1, 1)
} else {
days_from_civil(y, m + 1, 1)
};
let weekday = (first + 4).rem_euclid(7);
let mut day = first + (d - weekday).rem_euclid(7) + 7 * (w - 1);
if day >= next {
day -= 7;
}
day
}
}
}
}
/// The rule of a TZ string: a fixed offset, or standard and daylight saving
/// time with the local times of the two transitions in each year.
#[derive(Debug, Clone, Copy)]
enum Rule {
Fixed(i64),
Dst {
std: i64,
dst: i64,
start: (Day, i64),
end: (Day, i64),
},
}
impl Rule {
fn offset_at(self, t: i64) -> i64 {
match self {
Rule::Fixed(offset) => offset,
Rule::Dst {
std,
dst,
start,
end,
} => {
let (year, _, _) = civil_from_days((t + std).div_euclid(86_400));
let begin = start.0.days(year) * 86_400 + start.1 - std;
let finish = end.0.days(year) * 86_400 + end.1 - dst;
let in_dst = if begin < finish {
begin <= t && t < finish
} else {
!(finish <= t && t < begin)
};
if in_dst {
dst
} else {
std
}
}
}
}
}
struct TzString<'a> {
s: &'a [u8],
i: usize,
}
impl TzString<'_> {
fn peek(&self) -> Option<u8> {
self.s.get(self.i).copied()
}
fn eat(&mut self, c: u8) -> bool {
if self.peek() == Some(c) {
self.i += 1;
true
} else {
false
}
}
fn name(&mut self) -> Result<(), String> {
let begin = self.i;
if self.eat(b'<') {
while self.peek().is_some_and(|c| c != b'>') {
self.i += 1;
}
if !self.eat(b'>') {
return Err("unterminated zone abbreviation".into());
}
} else {
while self.peek().is_some_and(|c| c.is_ascii_alphabetic()) {
self.i += 1;
}
}
if self.i - begin < 3 {
Err("short zone abbreviation".into())
} else {
Ok(())
}
}
fn number(&mut self) -> Result<i64, String> {
let begin = self.i;
while self.peek().is_some_and(|c| c.is_ascii_digit()) {
self.i += 1;
}
std::str::from_utf8(&self.s[begin..self.i])
.ok()
.and_then(|n| n.parse().ok())
.ok_or_else(|| "expected a number".into())
}
/// [+-]hh[:mm[:ss]] in seconds.
fn time(&mut self) -> Result<i64, String> {
let sign = if self.eat(b'-') {
-1
} else {
self.eat(b'+');
1
};
let mut seconds = self.number()? * 3600;
if self.eat(b':') {
seconds += self.number()? * 60;
if self.eat(b':') {
seconds += self.number()?;
}
}
Ok(sign * seconds)
}
fn day(&mut self) -> Result<(Day, i64), String> {
let day = if self.eat(b'J') {
Day::Julian(self.number()?)
} else if self.eat(b'M') {
let m = self.number()?;
if !self.eat(b'.') {
return Err("expected .".into());
}
let w = self.number()?;
if !self.eat(b'.') {
return Err("expected .".into());
}
Day::MonthWeek(
u32::try_from(m).map_err(|e| e.to_string())?,
w,
self.number()?,
)
} else {
Day::Zero(self.number()?)
};
let time = if self.eat(b'/') { self.time()? } else { 7200 };
Ok((day, time))
}
/// The offsets in a TZ string are positive west of Greenwich, so they
/// are negated to get UTC offsets.
fn rule(&mut self) -> Result<Rule, String> {
self.name()?;
let std = -self.time()?;
if self.peek().is_none() {
return Ok(Rule::Fixed(std));
}
self.name()?;
let dst = match self.peek() {
Some(c) if c == b'+' || c == b'-' || c.is_ascii_digit() => -self.time()?,
_ => std + 3600,
};
if !self.eat(b',') {
return Err("TZ string without transition rules".into());
}
let start = self.day()?;
if !self.eat(b',') {
return Err("expected ,".into());
}
let end = self.day()?;
Ok(Rule::Dst {
std,
dst,
start,
end,
})
}
}
/// A time zone read from a TZif file.
#[derive(Debug)]
pub struct Zone {
transitions: Vec<i64>,
offsets: Vec<i64>,
first: i64,
rule: Option<Rule>,
}
fn be(b: &[u8]) -> i64 {
b.iter().fold(0, |n, &x| (n << 8) | i64::from(x))
}
impl Zone {
/// Reads the zone from the tz database in TZDIR or /usr/share/zoneinfo.
pub fn load(name: &str) -> Result<Zone, String> {
if name.is_empty() || name.starts_with('/') || name.split('/').any(|p| p == "..") {
return Err(format!("bad zone name {name}"));
}
let dir = std::env::var("TZDIR").unwrap_or_else(|_| "/usr/share/zoneinfo".into());
let data = fs::read(format!("{dir}/{name}")).map_err(|e| format!("{name}: {e}"))?;
Zone::parse(&data)
}
/// Parses a TZif file. For version 2 and later, the version 1 data block
/// is skipped and the 64-bit data block and the footer are used.
pub fn parse(data: &[u8]) -> Result<Zone, String> {
let bad = || "not a TZif file".to_string();
let header = |at: usize| -> Result<[usize; 6], String> {
let h = data.get(at..at + 44).ok_or_else(bad)?;
if &h[..4] != b"TZif" {
return Err(bad());
}
let mut counts = [0; 6];
for (k, c) in counts.iter_mut().enumerate() {
*c = be(&h[20 + 4 * k..24 + 4 * k]) as usize;
}
Ok(counts)
};
let block_len = |c: [usize; 6], size: usize| {
let [isut, isstd, leap, time, typ, chars] = c;
time * size + time + typ * 6 + chars + leap * (size + 4) + isstd + isut
};
let mut at = 0;
let mut counts = header(at)?;
let mut size = 4;
if data[4] >= b'2' {
at += 44 + block_len(counts, 4);
counts = header(at)?;
size = 8;
}
at += 44;
let [_, _, _, timecnt, typecnt, _] = counts;
let end = at + block_len(counts, size);
let block = data.get(at..end).ok_or_else(bad)?;
let signed = |b: &[u8]| {
let n = be(b);
if size == 4 {
i64::from(n as u32 as i32)
} else {
n
}
};
let transitions: Vec<i64> = (0..timecnt)
.map(|i| signed(&block[i * size..(i + 1) * size]))
.collect();
let index = &block[timecnt * size..timecnt * (size + 1)];
let types = &block[timecnt * (size + 1)..timecnt * (size + 1) + typecnt * 6];
let utoff = |k: usize| i64::from(be(&types[k * 6..k * 6 + 4]) as u32 as i32);
if typecnt == 0 {
return Err(bad());
}
let offsets = index.iter().map(|&k| utoff(usize::from(k))).collect();
let mut rule = None;
if size == 8 && data.get(end) == Some(&b'\n') {
let rest = &data[end + 1..];
let footer = &rest[..rest.iter().position(|&c| c == b'\n').unwrap_or(rest.len())];
if !footer.is_empty() {
rule = Some(TzString { s: footer, i: 0 }.rule()?);
}
}
Ok(Zone {
transitions,
offsets,
first: utoff(0),
rule,
})
}
/// The UTC offset, in seconds, at t seconds after the epoch.
pub fn offset_at(&self, t: i64) -> i64 {
match self.transitions.last() {
Some(&last) if t >= last => self
.rule
.map_or(self.offsets[self.offsets.len() - 1], |r| r.offset_at(t)),
None => self.rule.map_or(self.first, |r| r.offset_at(t)),
_ => match self.transitions.partition_point(|&x| x <= t) {
0 => self.first,
n => self.offsets[n - 1],
},
}
}
/// The instant of a local time, given as seconds after the epoch as if
/// it were UTC. A time in a gap moves forward by the length of the gap,
/// and a time in an overlap gives the earlier of its two instants.
pub fn local_to_instant(&self, local: i64) -> i64 {
let before = self.offset_at(local - 86_400);
let after = self.offset_at(local + 86_400);
[before, after]
.into_iter()
.map(|offset| local - offset)
.filter(|&u| local - u == self.offset_at(u))
.min()
.unwrap_or(local - before)
}
}
/// Returns the local time in to_zone for a local time in from_zone, as
/// YYYY-MM-DDTHH:MM:SS+HH:MM.
#[allow(clippy::too_many_arguments)]
pub fn convert_time_zone(
year: i64,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
from_zone: &str,
to_zone: &str,
) -> Result<String, String> {
let from = Zone::load(from_zone)?;
let to = Zone::load(to_zone)?;
let local = days_from_civil(year, month, day) * 86_400
+ i64::from(hour) * 3600
+ i64::from(minute) * 60
+ i64::from(second);
let instant = from.local_to_instant(local);
let offset = to.offset_at(instant);
let there = instant + offset;
let (y, m, d) = civil_from_days(there.div_euclid(86_400));
let s = there.rem_euclid(86_400);
let sign = if offset < 0 { '-' } else { '+' };
let a = offset.abs();
Ok(format!(
"{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}{sign}{:02}:{:02}",
s / 3600,
s % 3600 / 60,
s % 60,
a / 3600,
a % 3600 / 60
))
}
tests/tzconv_test.rs 289 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-between-time-zones/.
use algo_convert_between_time_zones::{convert_time_zone, Zone};
#[allow(clippy::type_complexity)]
const CASES: &[(&str, i64, u32, u32, u32, u32, u32, &str, &str, &str)] = &[
(
"new-york-to-utc",
2024,
7,
1,
12,
0,
0,
"America/New_York",
"UTC",
"2024-07-01T16:00:00+00:00",
),
(
"utc-to-tokyo",
2024,
1,
15,
0,
0,
0,
"UTC",
"Asia/Tokyo",
"2024-01-15T09:00:00+09:00",
),
(
"london-to-new-york",
2024,
1,
15,
12,
0,
0,
"Europe/London",
"America/New_York",
"2024-01-15T07:00:00-05:00",
),
(
"date-changes",
2024,
1,
15,
22,
0,
0,
"America/Los_Angeles",
"Asia/Tokyo",
"2024-01-16T15:00:00+09:00",
),
(
"same-zone",
2024,
3,
10,
12,
0,
0,
"America/New_York",
"America/New_York",
"2024-03-10T12:00:00-04:00",
),
(
"nonexistent-time",
2024,
3,
10,
2,
30,
0,
"America/New_York",
"UTC",
"2024-03-10T07:30:00+00:00",
),
(
"ambiguous-time",
2024,
11,
3,
1,
30,
0,
"America/New_York",
"UTC",
"2024-11-03T05:30:00+00:00",
),
(
"ambiguous-time-london",
2024,
10,
27,
1,
30,
0,
"Europe/London",
"UTC",
"2024-10-27T00:30:00+00:00",
),
(
"dst-dates-differ",
2024,
3,
20,
12,
0,
0,
"America/New_York",
"Europe/London",
"2024-03-20T16:00:00+00:00",
),
(
"southern-hemisphere",
2024,
1,
15,
12,
0,
0,
"Australia/Sydney",
"UTC",
"2024-01-15T01:00:00+00:00",
),
(
"half-hour-offset",
2024,
1,
15,
12,
0,
0,
"Asia/Kolkata",
"UTC",
"2024-01-15T06:30:00+00:00",
),
(
"45-minute-offset",
2024,
1,
15,
12,
0,
0,
"UTC",
"Asia/Kathmandu",
"2024-01-15T17:45:00+05:45",
),
(
"half-hour-dst",
2024,
1,
15,
12,
0,
0,
"Australia/Lord_Howe",
"UTC",
"2024-01-15T01:00:00+00:00",
),
(
"across-the-date-line",
2024,
1,
15,
12,
0,
0,
"Pacific/Kiritimati",
"Pacific/Pago_Pago",
"2024-01-14T11:00:00-11:00",
),
(
"before-skipped-day",
2011,
12,
29,
12,
0,
0,
"Pacific/Apia",
"UTC",
"2011-12-29T22:00:00+00:00",
),
(
"skipped-day",
2011,
12,
30,
12,
0,
0,
"Pacific/Apia",
"UTC",
"2011-12-30T22:00:00+00:00",
),
(
"after-skipped-day",
2011,
12,
31,
12,
0,
0,
"Pacific/Apia",
"UTC",
"2011-12-30T22:00:00+00:00",
),
(
"old-dst-rule",
2006,
3,
15,
12,
0,
0,
"America/New_York",
"UTC",
"2006-03-15T17:00:00+00:00",
),
(
"posix-sign",
2024,
1,
15,
12,
0,
0,
"UTC",
"Etc/GMT+5",
"2024-01-15T07:00:00-05:00",
),
(
"result-before-epoch",
1970,
1,
1,
0,
0,
0,
"UTC",
"America/New_York",
"1969-12-31T19:00:00-05:00",
),
(
"far-future",
2050,
7,
1,
12,
0,
0,
"America/New_York",
"UTC",
"2050-07-01T16:00:00+00:00",
),
];
#[test]
fn cases() {
for &(name, year, month, day, hour, minute, second, from, to, want) in CASES {
assert_eq!(
convert_time_zone(year, month, day, hour, minute, second, from, to).as_deref(),
Ok(want),
"{name}"
);
}
}
// After the last transition in the file, the TZ string footer gives the rules.
#[test]
fn footer_rules_match_transitions() {
let zone = Zone::load("America/New_York").unwrap();
// 2024-03-10 06:59:59 UTC and 07:00:00 UTC.
assert_eq!(zone.offset_at(1_710_053_999), -18_000);
assert_eq!(zone.offset_at(1_710_054_000), -14_400);
// 2100-03-14 is the second Sunday of March 2100.
assert_eq!(zone.offset_at(4_108_690_800 - 1), -18_000);
assert_eq!(zone.offset_at(4_108_690_800), -14_400);
}
#[test]
fn unknown_zone() {
assert!(convert_time_zone(2024, 1, 1, 0, 0, 0, "Mars/Olympus", "UTC").is_err());
assert!(convert_time_zone(2024, 1, 1, 0, 0, 0, "../etc/passwd", "UTC").is_err());
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-between-time-zones/.
# The functions need GNU date for -d @SECONDS and %:z.
# _tz_offset ZONE SECONDS
# Prints the UTC offset of ZONE, in seconds, at SECONDS after the epoch.
_tz_offset() {
local z sign=1
z=$(TZ="$1" date -d "@$2" +%z) || return 1
[[ $z == -* ]] && sign=-1
echo "$((sign * (10#${z:1:2} * 3600 + 10#${z:3:2} * 60)))"
}
# _tz_check ZONE
# With an unknown TZ value, date uses UTC and reports no error, so the zone
# file is checked first.
_tz_check() {
case $1 in
"" | /* | *..*) return 1 ;;
esac
[[ -r ${TZDIR:-/usr/share/zoneinfo}/$1 ]]
}
# convert_time_zone YEAR MONTH DAY HOUR MINUTE SECOND FROM_ZONE TO_ZONE
# Prints the local time in TO_ZONE as YYYY-MM-DDTHH:MM:SS+HH:MM. A time in a
# gap moves forward by the length of the gap, and a time in an overlap gives
# the earlier of its two instants.
convert_time_zone() {
local from=$7 to=$8 t before after offset u instant=
_tz_check "$from" || { echo "unknown zone: $from" >&2; return 1; }
_tz_check "$to" || { echo "unknown zone: $to" >&2; return 1; }
t=$(date -u -d "$(printf '%04d-%02d-%02d %02d:%02d:%02d' "$1" "$2" "$3" "$4" "$5" "$6")" +%s) || return 1
before=$(_tz_offset "$from" "$((t - 86400))")
after=$(_tz_offset "$from" "$((t + 86400))")
for offset in "$before" "$after"; do
u=$((t - offset))
if [[ $(_tz_offset "$from" "$u") == "$offset" ]] && [[ -z $instant || $u -lt $instant ]]; then
instant=$u
fi
done
: "${instant:=$((t - before))}"
TZ="$to" date -d "@$instant" +%Y-%m-%dT%H:%M:%S%:z
}
test_tzconv.bats 30 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-between-time-zones/.
setup() {
source "$BATS_TEST_DIRNAME/tzconv.sh"
}
@test "new-york-to-utc" { run convert_time_zone 2024 7 1 12 0 0 America/New_York UTC; [ "$status" -eq 0 ]; [ "$output" = "2024-07-01T16:00:00+00:00" ]; }
@test "utc-to-tokyo" { run convert_time_zone 2024 1 15 0 0 0 UTC Asia/Tokyo; [ "$status" -eq 0 ]; [ "$output" = "2024-01-15T09:00:00+09:00" ]; }
@test "london-to-new-york" { run convert_time_zone 2024 1 15 12 0 0 Europe/London America/New_York; [ "$status" -eq 0 ]; [ "$output" = "2024-01-15T07:00:00-05:00" ]; }
@test "date-changes" { run convert_time_zone 2024 1 15 22 0 0 America/Los_Angeles Asia/Tokyo; [ "$status" -eq 0 ]; [ "$output" = "2024-01-16T15:00:00+09:00" ]; }
@test "same-zone" { run convert_time_zone 2024 3 10 12 0 0 America/New_York America/New_York; [ "$status" -eq 0 ]; [ "$output" = "2024-03-10T12:00:00-04:00" ]; }
@test "nonexistent-time" { run convert_time_zone 2024 3 10 2 30 0 America/New_York UTC; [ "$status" -eq 0 ]; [ "$output" = "2024-03-10T07:30:00+00:00" ]; }
@test "ambiguous-time" { run convert_time_zone 2024 11 3 1 30 0 America/New_York UTC; [ "$status" -eq 0 ]; [ "$output" = "2024-11-03T05:30:00+00:00" ]; }
@test "ambiguous-time-london" { run convert_time_zone 2024 10 27 1 30 0 Europe/London UTC; [ "$status" -eq 0 ]; [ "$output" = "2024-10-27T00:30:00+00:00" ]; }
@test "dst-dates-differ" { run convert_time_zone 2024 3 20 12 0 0 America/New_York Europe/London; [ "$status" -eq 0 ]; [ "$output" = "2024-03-20T16:00:00+00:00" ]; }
@test "southern-hemisphere" { run convert_time_zone 2024 1 15 12 0 0 Australia/Sydney UTC; [ "$status" -eq 0 ]; [ "$output" = "2024-01-15T01:00:00+00:00" ]; }
@test "half-hour-offset" { run convert_time_zone 2024 1 15 12 0 0 Asia/Kolkata UTC; [ "$status" -eq 0 ]; [ "$output" = "2024-01-15T06:30:00+00:00" ]; }
@test "45-minute-offset" { run convert_time_zone 2024 1 15 12 0 0 UTC Asia/Kathmandu; [ "$status" -eq 0 ]; [ "$output" = "2024-01-15T17:45:00+05:45" ]; }
@test "half-hour-dst" { run convert_time_zone 2024 1 15 12 0 0 Australia/Lord_Howe UTC; [ "$status" -eq 0 ]; [ "$output" = "2024-01-15T01:00:00+00:00" ]; }
@test "across-the-date-line" { run convert_time_zone 2024 1 15 12 0 0 Pacific/Kiritimati Pacific/Pago_Pago; [ "$status" -eq 0 ]; [ "$output" = "2024-01-14T11:00:00-11:00" ]; }
@test "before-skipped-day" { run convert_time_zone 2011 12 29 12 0 0 Pacific/Apia UTC; [ "$status" -eq 0 ]; [ "$output" = "2011-12-29T22:00:00+00:00" ]; }
@test "skipped-day" { run convert_time_zone 2011 12 30 12 0 0 Pacific/Apia UTC; [ "$status" -eq 0 ]; [ "$output" = "2011-12-30T22:00:00+00:00" ]; }
@test "after-skipped-day" { run convert_time_zone 2011 12 31 12 0 0 Pacific/Apia UTC; [ "$status" -eq 0 ]; [ "$output" = "2011-12-30T22:00:00+00:00" ]; }
@test "old-dst-rule" { run convert_time_zone 2006 3 15 12 0 0 America/New_York UTC; [ "$status" -eq 0 ]; [ "$output" = "2006-03-15T17:00:00+00:00" ]; }
@test "posix-sign" { run convert_time_zone 2024 1 15 12 0 0 UTC Etc/GMT+5; [ "$status" -eq 0 ]; [ "$output" = "2024-01-15T07:00:00-05:00" ]; }
@test "result-before-epoch" { run convert_time_zone 1970 1 1 0 0 0 UTC America/New_York; [ "$status" -eq 0 ]; [ "$output" = "1969-12-31T19:00:00-05:00" ]; }
@test "far-future" { run convert_time_zone 2050 7 1 12 0 0 America/New_York UTC; [ "$status" -eq 0 ]; [ "$output" = "2050-07-01T16:00:00+00:00" ]; }
@test "unknown-zone" { run convert_time_zone 2024 1 1 0 0 0 Mars/Olympus UTC; [ "$status" -eq 1 ]; }
References
- The Python Standard Library, zoneinfo, Using ZoneInfo
- PEP 495, Local Time Disambiguation, Mind the Gap
- Java SE 21 API, java.time.ZonedDateTime, the description of the class; withZoneSameInstant; withZoneSameLocal
- .NET API reference, TimeZoneInfo.ConvertTime, ConvertTime(DateTime, TimeZoneInfo, TimeZoneInfo), Exceptions and Remarks
- Go standard library, time, func Date
- cppreference.com, std::chrono::local_info, the description of the members
- cppreference.com, std::chrono::choose, the description of the enumeration
- MDN, Intl.DateTimeFormat() constructor, timeZone; Exceptions
- RFC 9636, The Time Zone Information Format (TZif), Section 3.2, TZif Data Block; Section 3.3, TZif Footer
- Theory and pragmatics of the tz code and data, Scope of the tz database
- The tz database, the source file etcetera, the comment before the Etc/GMT zones
- Linux manual page, tzset(3), DESCRIPTION
- Linux manual page, date(1), the format sequences %z and %:z
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag Q8JZN5 Edit this page History Report an error Markdown