Calendar and Time-Zones in C++20: Time-Zones


This post concludes my introduction to the chrono extension in C++20. Today I present the time-zones functionality.


I should have written, today I mainly present the time-zones functionality in C++20. Before I write about the time-zones in C++20, I want to present the online resource Examples and Recipes from Howard Hinnant, which has about 40 examples of the new chrono functionality. Presumably, the chrono extension in C++20 is not easy to get; therefore it's quite important to have so many examples. You should use these examples as a starting point for further experiments and, therefore, sharpen your understanding. You can also add your recipes.

To get an idea of Examples and Recipes I want to present a program for Roland Bock that calculates ordinal dates.

Calculating Ordinal Dates

"An ordinal date consists of a year and a day of year (1st of January being day 1, 31st of December being day 365 or day 366). The year can be obtained directly from year_month_day. And calculating the day is wonderfully easy. In the code below we make us of the fact that year_month_day can deal with invalid dates like the 0th of January:" (Roland Bock)

I added the necessary headers to Roland's program.

// ordinalDate.cpp

#include "date.h"
#include <iomanip>
#include <iostream>

int main()
   using namespace date;
   const auto time = std::chrono::system_clock::now();
   const auto daypoint = floor<days>(time);                    // (1) 
   const auto ymd = year_month_day{daypoint};         
   // calculating the year and the day of the year
   const auto year = ymd.year();
   const auto year_day = daypoint - sys_days{year/January/0}; // (2) 
                                                              // (3)
   std::cout << year << '-' << std::setfill('0') << std::setw(3) << year_day.count() << std::endl;
   // inverse calculation and check
   assert(ymd == year_month_day{sys_days{year/January/0} + year_day});


I want to add a few remarks to the program. Line (1) truncates the current time point. The value is used in the following line to initialize a calendar date. Line (2) calculates the time duration between the two-time points. Both time points have the resolution day. Finally, year_day.count() inline (3) returns the time duration in days.ordinalDate2

My following examples to time-zones are also inspired by the already mentioned web resource Examples and Recipes.


First of all, a time-zone is a region and its full history of the date such as daylight saving time or leap seconds. The time-zone library in C++20 is a complete parser of the IANA timezone database. The following table should give you a first idea of the new functionality.


I use in my examples the function std::chrono::zones_time which is essentially a time zone combined with a time point.

Before I show you two examples I want to make a short remark. To compile a program using the time-zone library, you have to compile the tz.cpp file and link it against the curl library. The curl library is necessary to get the current IANA timezone database. The following command line for g++ should give you the idea:

g++ localTime.cpp -I <Path to data/tz.h> tz.cpp -std=c++17 -lcurl -o localTime


My first program is straightforward. It displays the UTC time and the local time.

UTC Time and Local Time

The UTC time or Coordinated Univeral Time is the primary time standard worldwide. A computer uses Unix time which is a very close approximation of UTC. The UNIX time is the number of seconds since the Unix epoch. The Unix epoch is 00:00:00 UTC on 1 January 1970.

std::chrono::system_clock::now() inline (1) returns in the following program localTime.cpp the Unix time.


// localTime.cpp

#include "date/tz.h"
#include <iostream>

int main() {

    std::cout << std::endl;

    using namespace date;
    std::cout << "UTC  time" << std::endl;             // (1)
    auto utcTime = std::chrono::system_clock::now();
    std::cout << "  " << utcTime << std::endl;
    std::cout << "  " << date::floor<std::chrono::seconds>(utcTime) << '\n':

    std::cout << std::endl;
    std::cout << "Local time" << std::endl;            // (2)
    auto localTime = date::make_zoned(date::current_zone(), utcTime);
    std::cout << "  " << localTime << std::endl;
    std::cout << "  " << date::floor<std::chrono::seconds>(localTime.get_local_time()) 
            << std::endl;

    auto offset = localTime.get_info().offset;         // (3)
    std::cout << "  UTC offset: "  << offset << std::endl;

    std::cout << std::endl;



I have not to add too much to the program. The code block beginning with line (1) gets the current time point, truncates it to seconds, and displays it. The call date::make_zoned creates  std::chrono::zoned_time localTime. The following call localTime.get_local_time() returns the stored time point as a local time. This time point is also truncated to seconds. localTime (line 3) can also be used to get information about the time zone. In this case, I'm interested in the offset to the UTC time.


My last program answers a crucial question when I teach in a different time zone: When should I start my online class?

Various Time-Zones for Online Classes

The program onlineClass.cpp answers the following question: How late is it in given time-zones, when I start an online class at the 7h, 13h, or 17h local time (Germany)?

The online class should start on the 1st of February 2021 and should take 4 hours. Because of daylight saving time, the calendar date is essential to get the correct answer.


// onlineClass.cpp

#include "date/tz.h"
#include <algorithm>
#include <iomanip>
#include <iostream>

template <typename ZonedTime>
auto getMinutes(const ZonedTime& zonedTime) {                         // (1)
    return date::floor<std::chrono::minutes>(zonedTime.get_local_time());

void printStartEndTimes(const date::local_days& localDay,            // (2)
                        const std::chrono::hours& h, 
                        const std::chrono::hours& durationClass,
                        const std::initializer_list<std::string>& timeZones ){
    date::zoned_time startDate{date::current_zone(), localDay + h};  // (4)
    date::zoned_time endDate{date::current_zone(), localDay + h + durationClass};
    std::cout << "Local time: ["  << getMinutes(startDate) << ", " 
                                  << getMinutes(endDate) << "]" << std::endl;
// (5)
longestStringSize = std::max(timeZones, [](const std::string& a, const std::string& b) { return a.size() < b.size(); }).size(); for (auto timeZone: timeZones) { // (6) std::cout << " " << std::setw(longestStringSize + 1) << std::left << timeZone << "[" << getMinutes(date::zoned_time(timeZone, startDate)) << ", " << getMinutes(date::zoned_time(timeZone, endDate)) << "]" << std::endl; } } int main() { using namespace std::string_literals; using namespace std::chrono; std::cout << std::endl; constexpr auto classDay{date::year(2021)/2/1}; constexpr auto durationClass = 4h; auto timeZones = {"America/Los_Angeles"s, "America/Denver"s, "America/New_York"s, "Europe/London"s, "Europe/Minsk"s, "Europe/Moscow"s, "Asia/Kolkata"s, "Asia/Novosibirsk"s, "Asia/Singapore"s, "Australia/Perth"s, "Australia/Sydney"s}; for (auto startTime: {7h, 13h, 17h}) { // (3) printStartEndTimes(date::local_days{classDay}, startTime, durationClass, timeZones); std::cout << std::endl; } }


Before I dive into the functions getMinutes (line 1) and printStartEndTimes (line 2), let me say a view words about the main function. The main function defines the day of the class, the duration of the class, and all time zones. Finally, the range-based for-loop (line 3) iterates through all potential starting points for an online class. Thanks to the function printStartEndTimes (line 2) all necessary information are displayed.

The few lines beginning with line (4) calculate the startDate and endDate of my training by adding the start time and the duration of the class to the calendar date. Both values are displayed with the help of the function getMinutes (line 1). date::floor<std::chrono::minutes>(zonedTime.get_local_time()) gets the stored time point out of the std::chrono::zoned_time and truncates the value to the minute resolution. To properly align the output of the program, line (5) determines the size of the longest of all time-zone names. Line (6) iterates through all time zones and displays the name of the time-zone, and the beginning and end of each online class. A few calendar dates even cross the day boundaries.onlineClass

There is more to write about in the extended Chrono library. For example, C++20 offers new clocks such as std::chrono::utc_clock that include leap seconds, or the std::chrono::tai_clock that represents the International Atomic Time (TAI). Additional, thanks to the new formatting library in C++20, time durations can be nicely formatted. This feature is not available so far. If you want to study the formating rules for time durations, here are they: std::formatter.

What's next?

If you want to compare signed and unsigned integrals, you may have a lot of fun. This fun ends with C++20.



Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Tobi Heideman, Daniel Hufschläger, Red Trip, Alexander Schwarz, Tornike Porchxidze, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Dimitrov Tsvetomir, Leo Goodstadt, Eduardo Velasquez, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, and Michael Young.


Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, and Bhushan Ivatury.



My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small



I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)


Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.


Contact Me

Modernes C++,





Tags: time

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code


Today 2966

Yesterday 5806

Week 2966

Month 172383

All 7440223

Currently are 183 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments