Daily bit(e) of C++ | std::chrono — time zones
Daily bit(e) of C++ ♻️76, Handling time zones and zoned times using C++20 std::chrono.
Time zones are a particularly annoying problem when dealing with time. The C++20 extension to std::chrono also introduced support for time zones.
The list of supported time zones can be queried through the time zone database. Alternatively, a time zone can be located directly using its name.
While std::chrono::sys_time is always UTC, the library now also supports unzoned time in the form of std::chrono::local_time. Unzoned time can be combined with a specific time zone to produce a std::chrono::zoned_time, which can then be converted to other time zones.
#include <chrono>
#include <ranges>
using namespace std::chrono;
// Time zone database version
std::string tzdb_version = std::chrono::remote_version();
// Iterate over valid timezones
for (auto& zone : get_tzdb().zones) {
// zone.name()
}
// USA switch to summer time
std::chrono::year_month_day usa_summer{2025y/March/Sunday[2]};
// 2025-03-09
// Europe switch to summer time
std::chrono::year_month_day eu_summer{2025y/March/Sunday[last]};
// 2025-03-30
// Locate two time zones in the time zone db
// that we will be working with
auto prague = std::chrono::locate_zone("Europe/Prague");
auto newyork = std::chrono::locate_zone("America/New_York");
// Let's simulate a weekly meeting on Wednesday 15:00 Prague time
// Local time is unzoned
std::chrono::local_time meeting{local_days{2025y/March/Wednesday[1]}};
// Iterate over all meetings until summer time change
while (meeting < local_days{2025y/April/Sunday[1]}) {
// create zoned time for Prague
zoned_time<seconds> local{prague, local_days{meeting} + 15h};
// create zoned time for NewYork from the Prague zoned time
zoned_time<seconds> remote{newyork, local};
std::println("{}: {}", prague->name(), local);
std::println("{}: {}\n", newyork->name(), remote);
meeting += weeks{1};
}
/* Will print:
Europe/Prague: 2025-03-05 15:00:00
America/New_York: 2025-03-05 09:00:00
Europe/Prague: 2025-03-12 15:00:00
America/New_York: 2025-03-12 10:00:00
Europe/Prague: 2025-03-19 15:00:00
America/New_York: 2025-03-19 10:00:00
Europe/Prague: 2025-03-26 15:00:00
America/New_York: 2025-03-26 10:00:00
Europe/Prague: 2025-04-02 15:00:00
America/New_York: 2025-04-02 09:00:00
*/