How to convert std::chrono::time_point
to string?
For example: \"201601161125\"
.
The following function converts from chrono
time_point
to string (serialization).
#include
#include
#include
using time_point = std::chrono::system_clock::time_point;
std::string serializeTimePoint( const time_point& time, const std::string& format)
{
std::time_t tt = std::chrono::system_clock::to_time_t(time);
std::tm tm = *std::gmtime(&tt); //GMT (UTC)
//std::tm tm = *std::localtime(&tt); //Locale time-zone, usually UTC by default.
std::stringstream ss;
ss << std::put_time( &tm, format.c_str() );
return ss.str();
}
// example
int main()
{
time_point input = std::chrono::system_clock::now();
std::cout << serializeTimePoint(input, "UTC: %Y-%m-%d %H:%M:%S") << std::endl;
}
The time_point
data-type has no internal representation for the time-zone, in consequence, the time-zone is aggregated by the conversion to std::tm
(by the functions gmtime
or localtime
). It is not recommended to add/substract the time-zone from the input, because you would get an incorrect time-zone displayed with %Z
, thus, it is better to set the correct local time (OS dependent) and use localtime()
.
For technical usage, hard-coded time format is a good solution. However, to display to users, one should use a locale
to retrieve the user preference and show time-stamp in that format.
Since C++20, we have nice serialization and parsing functions for time_point and duration.
std::chrono::to_stream
std::chrono::format