Calendars and time zones in C++20

Understanding the basics of the new <std::chrono> features

CMP

--

C++ has been known for its powerful and efficient time and date functionalities since the introduction of the <std::chrono> library in C++11. The std::chrono::duration class allowed for time interval representation with various duration types such as std::chrono::seconds, and the time_point class and various types of clocks allowed for the representation of a single point in time.

With the introduction of C++20, not only have these existing classes been enhanced with things like std::chrono::utc_clock and other types of clocks, but new classes have been added to add support for calendars and time zones. These features make working with dates and times even more flexible and intuitive.

Working with calendars in C++20

Look at the following example of displaying the current calendar day:

#include <chrono>
#include <iostream>

int main() {
const std::chrono::time_point now{std::chrono::system_clock::now()};
const std::chrono::year_month_day ymd{std::chrono::floor<std::chrono::days>(now)};

std::cout << "Current Year: " << static_cast<int>(ymd.year()) << ", "
"Month: " << static_cast<unsigned>(ymd.month()) << ", "
"Day: " << static_cast<unsigned>(ymd.day()) << "\n"
"ymd: " << ymd << std::endl;
}
Current Year: 2024, Month: 8, Day: 4
ymd: 2024-08-04

--

--

CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.