How to convert std::chrono::time_point
to string?
For example: \"201601161125\"
.
Howard Hinnant's free, open source, header-only, portable date/time library is a modern way to do this that doesn't traffic through the old C API, and doesn't require that you discard all of your sub-second information. This library is also being proposed for standardization.
There is a lot of flexibility in formatting. The easiest way is to just stream out:
#include "date.h"
#include
int
main()
{
using namespace date;
std::cout << std::chrono::system_clock::now() << '\n';
}
This just output for me:
2017-09-15 13:11:34.356648
The using namespace date;
is required in order to find the streaming operator for the system_clock::time_point
(it isn't legal for my lib to insert it into namespace std::chrono
). No information is lost in this format: the full precision of your system_clock::time_point
will be output (microseconds
where I ran this on macOS).
The full suite of strftime-like formatting flags is available for other formats, with minor extensions to handle things like fractional seconds. Here is another example that outputs with millisecond precision:
#include "date.h"
#include
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << format("%D %T %Z\n", floor(system_clock::now()));
}
which just output for me:
09/15/17 13:17:40.466 UTC