The process of transforming a std::chrono::timepoint into a string involves converting the timepoint into a timet object using std::chrono::systemclock::totimet() function, and then using the std::localtime() function to convert the time_t object into a struct tm object in local time. Once we have the struct tm object, we can use std::strftime() function to format the time as a string according to a specified format string. Here's an example code snippet:
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
std::string time_point_to_string(const std::chrono::system_clock::time_point& time_point, const std::string& format="%Y-%m-%d %H:%M:%S") {
std::time_t time_t = std::chrono::system_clock::to_time_t(time_point);
std::tm tm = *std::localtime(&time_t);
std::stringstream ss;
ss << std::put_time(&tm, format.c_str());
return ss.str();
}
The above code defines a function time_point_to_string()
that takes a time_point as input, and returns a string in the specified format. The default format is %Y-%m-%d %H:%M:%S
, which corresponds to "year-month-day hour:minute:second".
To use the function, we can pass a time_point object to it, along with an optional format string:
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::string str = time_point_to_string(now, "%Y/%m/%d %I:%M:%S %p");
This will return a string in the format "year/month/day hour:minute:second AM/PM", such as "2021/10/25 04:30:15 PM".
Asked: 2021-07-06 11:00:00 +0000
Seen: 9 times
Last updated: May 23 '22