I have the following code, using Date library:
#include "date.h"
#include <iostream>
#include <sstream>
using namespace date;
using namespace std::chrono;
int main()
{
auto now = system_clock::now();
std::stringstream ss;
ss << now;
std::string nowStr = ss.str(); // I need a string
std::cout << nowStr << " UTC\n";
}
The result is:
2020-03-26 17:38:24.473372486 UTC
Is stringstream the correct approach to obtain a string from the chrono::timepoint that now() returns? And, if so, how can I round those nanoseconds to milliseconds?
Yes, ostringstream
is a good way to do this. You could also use date::format
which returns a string
, but this still uses a ostringstream
internally:
string s = format("%F %T %Z", now);
With either technique, you can truncate to milliseconds
output by truncating the input time_point
to milliseconds
prior to formatting it. You can choose any of these rounding modes:
time_point_cast<milliseconds>(now)
floor<milliseconds>(now)
ceil<milliseconds>(now)
round<milliseconds>(now)
-
string s = format("%F %T %Z", floor<milliseconds>(now));
2020-03-26 17:38:24.473 UTC
In C++20 this will become:
string s = format("{:%F %T %Z}", floor<milliseconds>(now));