Skip to content

Instantly share code, notes, and snippets.

@IMelker
Last active Oct 22, 2020
Embed
What would you like to do?
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