What is the prettiest way to convert time_point to string?
Simple question, how to properly convert std::chrono::time_point
to a std::string
with as little code as possible?
Notes: I don't want to use cout
it with put_time()
. C++11 and C++14 solutions are accepted.
Using only standard library headers (works with >= C++11):
#include <ctime>
#include <chrono>
#include <string>
using sc = std::chrono::system_clock ;
std::time_t t = sc::to_time_t(sc::now());
char buf[20];
strftime(buf, 20, "%d.%m.%Y %H:%M:%S", localtime(&t));
std::string s(buf);
#include "date/date.h"
#include <type_traits>
int
main()
{
auto s = date::format("%F %T", std::chrono::system_clock::now());
static_assert(std::is_same<decltype(s), std::string>, "");
}
date/date.h
is found here. It is a header-only library, C++11/14/17. It has written documentation, and a video introduction.
Update:
In C++20 the syntax is:
#include <chrono>
#include <format>
#include <type_traits>
int
main()
{
auto s = std::format("{:%F %T}", std::chrono::system_clock::now());
static_assert(std::is_same_v<decltype(s), std::string>{});
}