Skip to content

Instantly share code, notes, and snippets.

@IMelker
Last active October 22, 2020 08:42
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 IMelker/fef5193221faa4d385e8a41ff99ea061 to your computer and use it in GitHub Desktop.
Save IMelker/fef5193221faa4d385e8a41ff99ea061 to your computer and use it in GitHub Desktop.
Get current time since epoch
#include <chrono>
#include <iomanip>
template <typename Clock>
class CurrentTime
{
template<struct tm* represent(const time_t *)>
static std::string utc() {
using namespace std::chrono;
auto timer = Clock::to_time_t(Clock::now());
std::tm bt = *represent(&timer);
std::ostringstream oss;
oss << std::put_time(&bt, "%F %T");
return oss.str();
}
template<struct tm* represent(const time_t *)>
static std::string utcWithMilli() {
using namespace std::chrono;
auto now = Clock::now();
auto ms = duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
auto timer = Clock::to_time_t(now);
std::tm bt = *represent(&timer);
std::ostringstream oss;
oss << std::put_time(&bt, "%F %T");
oss << '.' << std::setfill('0') << std::setw(3) << ms.count();
return oss.str();
}
public:
static long long seconds() {
using namespace std::chrono;
return duration_cast<seconds>(Clock::now().time_since_epoch()).count();
}
static long long milliseconds() {
using namespace std::chrono;
return duration_cast<milliseconds>(Clock::now().time_since_epoch()).count();
}
static long long microseconds() {
using namespace std::chrono;
return duration_cast<microseconds>(Clock::now().time_since_epoch()).count();
}
static long long nanoseconds() {
using namespace std::chrono;
return duration_cast<nanoseconds>(Clock::now().time_since_epoch()).count();
}
static std::string utcTime() { return CurrentTime::utc<&std::time>(); }
static std::string utcTimeWithMilli() { return CurrentTime::utcWithMilli<&std::time>(); }
static std::string utcLocalTime() { return CurrentTime::utc<&std::localtime>(); }
static std::string utcLocalTimeWithMilli() { return CurrentTime::utcWithMilli<&std::localtime>(); }
static std::string utcGMTime() { return CurrentTime::utc<&std::gmtime>(); }
static std::string utcGMTimeWithMilli() { return CurrentTime::utcWithMilli<&std::gmtime>(); }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment