Working with Dates in C++: Overview of Key Libraries
Working with dates and time is one of the fundamental tasks in programming. In C++, the standard library was long limited to utilities from C (<ctime>), which are inconvenient and type-unsafe. Starting with C++11 and especially C++20, the situation has changed dramatically. In this article, we will look at three main approaches to working with dates in modern C++.
1. Standard Library <chrono> (C++11 and C++20)
Starting with C++11, the standard library introduced the <chrono> header, providing type-safe clocks, time points (time_point), and durations (duration). In C++20, the library was extended with support for calendar types (year, month, day) and time zones.
Main Components:
std::chrono::system_clock— system clock tied to real time.std::chrono::steady_clock— monotonic clock for measuring intervals.std::chrono::duration— time interval (e.g., seconds, milliseconds).std::chrono::time_point— a point in time.- Calendar types (C++20):
year_month_day,hh_mm_ss, and others.
#include <iostream>#include <chrono>#include <format> // C++20
int main() { using namespace std::chrono;
// Current time auto now = system_clock::now(); std::cout << "Current time: " << now << "";
// Convert to calendar date (C++20) auto dp = floor<days>(now); year_month_day ymd{dp}; std::cout << "Year: " << (int)ymd.year() << "";
// Measuring interval auto start = steady_clock::now(); // ... some code ... auto end = steady_clock::now(); auto diff = end - start; std::cout << "Elapsed: " << duration_cast<milliseconds>(diff).count() << " ms"; return 0;}Pros: built into the standard, type-safe, actively developed.
Cons: C++20 requires a modern compiler (GCC 12+, Clang 14+, MSVC 2022).
2. Boost.DateTime
The Boost.DateTime library is one of the oldest and most mature for working with dates. Before the arrival of C++20, it was the de facto standard. It provides the boost::gregorian::date, boost::posix_time::ptime classes and full time zone support.
Main Features:
- Gregorian calendar with leap year support.
- Date manipulation: adding days, months, years.
- Formatting and parsing via
boost::date_time::date_facet. - Time zone support via
boost::local_time.
#include <iostream>#include <boost/date_time/gregorian/gregorian.hpp>#include <boost/date_time/posix_time/posix_time.hpp>
int main() { using namespace boost::gregorian; using namespace boost::posix_time;
// Creating a date date d(2024, 12, 25); std::cout << "Date: " << d << ""; // 2024-Dec-25
// Adding days date next_week = d + days(7); std::cout << "In a week: " << next_week << "";
// Difference between dates days diff = next_week - d; std::cout << "Difference: " << diff.days() << " days";
// Current time with second precision ptime now = second_clock::local_time(); std::cout << "Now: " << now << ""; return 0;}Pros: battle-tested, extensive documentation, works with C++98.