Working with Dates and Time in C++: From Classic to Modern Standard
Managing dates and time is one of the key tasks in software development. Whether it's event logging, deadline calculation, working with timers, or data analysis — reliable tools are essential. In C++, there are several approaches for this: from the classic <ctime> library to the modern <chrono>, which appeared in C++11 and was significantly expanded in C++20. In this article, we will break down the main methods for working with dates and time, provide practical examples, and show how to avoid common mistakes.
1. Classic Approach: The <ctime> Library
The <ctime> library came to C++ from the C language. It provides simple but limited tools for working with calendar time. The main types are: std::time_t (an integer number of seconds since January 1, 1970) and std::tm (a structure with fields for year, month, day, hours, minutes, seconds, etc.).
Example 1: Getting the current time and formatting
#include <iostream>#include <ctime>
int main() { // Get the current time std::time_t now = std::time(nullptr); // Convert to local time std::tm* local = std::localtime(&now); // Output in "YYYY-MM-DD HH:MM:SS" format char buffer[80]; std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local); std::cout << "Current time: " << buffer << std::endl; return 0;}Main <ctime> functions:
std::time()— returns the current calendar time.std::localtime()— convertstime_tto atmstructure representing local time.std::gmtime()— same, but for UTC (Coordinated Universal Time).std::mktime()— reverse conversion: fromtmtotime_t.std::difftime()— calculates the difference in seconds between two time points.std::strftime()— formats date and time into a string according to a given template.
Disadvantages: the library does not account for time zones (except local and UTC), does not support high precision (only seconds), and the tm structure is not type-safe (e.g., year is counted from 1900, month from 0 to 11).
2. Modern Standard: The <chrono> Library (C++11 and newer)
Starting with C++11, the <chrono> library was added to the standard library — a type-safe and high-precision library for working with time. It operates with three main concepts: duration, time_point, and clock.
Clock types:
std::chrono::system_clock— system time, tied to the calendar (can be converted totime_t).std::chrono::steady_clock— monotonic clock, ideal for measuring intervals (not subject to adjustments).std::chrono::high_resolution_clock— clock with the highest available resolution (often a synonym for steady_clock).
Example 2: Measuring operation execution time
#include <iostream>#include <chrono>#include <thread>
int main() { // Record the start auto start = std::chrono::steady_clock::now(); // Simulate work std::this_thread::sleep_for(std::chrono::milliseconds(500)); // Record the finish auto end = std::chrono::steady_clock::now(); // Calculate the difference auto duration = end - start;