Skip to content

Instantly share code, notes, and snippets.

@yohhoy
Last active December 15, 2021 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yohhoy/4f4c4262ef05fff084538672885ff359 to your computer and use it in GitHub Desktop.
Save yohhoy/4f4c4262ef05fff084538672885ff359 to your computer and use it in GitHub Desktop.
Ad-hoc std::ostream support for <chrono>
#include <ctime>
#include <chrono>
#include <iostream>
#include <iomanip>
namespace std {
// https://timsong-cpp.github.io/cppwp/n4868/time.cal.ymd.nonmembers#14
// "yyyy-mm-dd"
inline ostream& operator<<(ostream& os, const chrono::year_month_day& ymd) {
char prev = os.fill('0');
os << std::setw(4) << (int)ymd.year() << '-'
<< std::setw(2) << (unsigned)ymd.month() << '-'
<< std::setw(2) << (unsigned)ymd.day();
os.fill(prev);
return os;
}
// https://timsong-cpp.github.io/cppwp/n4868/time.clock.system.nonmembers#2
// "yyyy-mm-dd HH:MM:SS<.n>" (unspecified precision)
inline ostream& operator<<(ostream& os, const chrono::system_clock::time_point& tp) {
std::time_t t = chrono::system_clock::to_time_t(tp);
return os << std::put_time(std::gmtime(&t), "%F %T");
}
// https://timsong-cpp.github.io/cppwp/n4868/time.clock.system.nonmembers#4
// "yyyy-mm-dd"
inline ostream& operator<<(ostream& os, const chrono::sys_days& dp) {
return os << chrono::year_month_day{dp};
}
} // namespace std
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment