In C++, the std::chrono library provides powerful tools for date and time processing. However, std::chrono itself focuses on measuring time points (time_point) and durations (duration), rather than directly handling the formatted output of calendar dates and clock times. Starting from C++20, we can utilize new features in std::chrono for formatting date and time output. Prior to C++20, we typically combine std::chrono with other libraries, such as
The following is an example demonstrating how to use std::chrono and
cpp#include <iostream> #include <chrono> #include <ctime> int main() { // Get the current time point std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); // Convert to time_t to facilitate conversion to a human-readable format std::time_t now_time_t = std::chrono::system_clock::to_time_t(now); // Convert to local time std::tm* now_tm = std::localtime(&now_time_t); // Output the current date and time std::cout << "Current date and time: " << 1900 + now_tm->tm_year << '-' // Year << 1 + now_tm->tm_mon << '-' // Month << now_tm->tm_mday << ' ' // Day << now_tm->tm_hour << ':' // Hour << now_tm->tm_min << ':' // Minute << now_tm->tm_sec << std::endl; // Second return 0; }
In this example, we first use std::chrono::system_clock::now() to obtain the current time point. Then, we use std::chrono::system_clock::to_time_t() to convert the time point to time_t, which is easier to convert to a human-readable format. Using std::localtime() converts time_t to std::tm structure, which contains detailed breakdown of calendar dates and times.
Output example:
shellCurrent date and time: 2023-9-24 14:35:22
This method combines the high-precision time point measurement of std::chrono with traditional C library time formatting capabilities. For those requiring C++20 features, we can use std::format to directly format std::chrono types, which makes the code more concise and straightforward.