I want to provide a stream operator to output std::chrono::time_point as GMT date, I currently have the following (simplified for ostream only):
using datetime_t = std::chrono::system_clock::time_point;
std::ostream& operator<<(std::ostream &out, datetime_t dt) {
auto time = datetime_t::clock::to_time_t(dt);
auto under_sec =
std::chrono::duration_cast<std::chrono::milliseconds>(
dt.time_since_epoch() % std::chrono::seconds{1});
return out << std::put_time(std::gmtime(&time), "%Y-%m-%dT:%H:%M:%S")
<< "." << std::setfill('0') << std::setw(3) << under_sec.count();
}
Usage:
auto time = datetime_t::clock::now();
std::cout << time;
This works, but it forces the user to:
I would like to provide custom stream manipulator that would allow the user to modify both of these, e.g. for the second (assuming a namespace nm containing the manipulator):
std::cout << nm::us << time;
...that would print up to microseconds.
I already know how to create stream manipulators, e.g.:
namespace nm {
std::ios_base& us(std::ios_base &) { /* ... */ }
}
...but I don't know how to "store" the required information for use in the output operator.
Is there a simply way to "store" information in a stream (user-defined format flags?) to use in a later stream operation? Or another way to obtain slightly equivalent behavior?
As you've already discovered in your comments, yes, streams have, iword and pword storage. Not the easiest thing in the world to work with (designed decades ok), but serviceable.
Another option would be to use an already coded library for this such as Howard Hinnant's free, open source, datetime library:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << format("%FT:%T", floor<microseconds>(system_clock::now())) << '\n';
}
With this library the precision of the output is controlled by adjusting the precision of the input (i.e. with time_point_cast or floor).
Sample output:
2017-07-10T:11:46:59.354321
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With