Skip to content

Instantly share code, notes, and snippets.

@elbeno
Last active August 15, 2016 21:43
Show Gist options
  • Save elbeno/a688b9052e875276f0a127299d56e695 to your computer and use it in GitHub Desktop.
Save elbeno/a688b9052e875276f0a127299d56e695 to your computer and use it in GitHub Desktop.
Time functionality snippets
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <algorithm>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
inline time_t to_time_t(const std::chrono::system_clock::time_point& tp)
{
// assume that a time_t is in seconds since 1/1/1970 UTC
// and a system_clock::time_point has the same epoch
return std::chrono::duration_cast<std::chrono::seconds>(
tp.time_since_epoch()).count();
}
std::chrono::system_clock::duration get_tz_offset(bool include_dst = true)
{
time_t now = time(nullptr);
auto utc = std::gmtime(&now);
time_t now_utc = mktime(utc);
auto local = std::localtime(&now);
time_t now_local = mktime(local);
if (include_dst && local->tm_isdst) now_local += 60 * 60;
auto offset = difftime(now_local, now_utc);
return std::chrono::seconds(static_cast<int64_t>(offset));
}
inline std::chrono::system_clock::time_point to_local(
const std::chrono::system_clock::time_point& tp)
{
static auto tz_offset = get_tz_offset();
return tp + tz_offset;
}
std::string to_iso_string(const std::chrono::system_clock::time_point& tp)
{
auto t = to_time_t(tp);
auto gmt = std::gmtime(&t);
std::stringstream ss;
ss << std::put_time(gmt, "%Y%m%dT%H%M%S.");
auto tp_secs = std::chrono::system_clock::time_point{}
+ std::chrono::seconds(t);
auto usecs = std::chrono::duration_cast<std::chrono::microseconds>(
tp - tp_secs);
ss << std::setw(6) << std::setfill('0') << usecs.count();
return ss.str();
}
std::string to_log_string(const std::chrono::system_clock::time_point& tp)
{
auto t = to_time_t(tp);
auto gmt = std::gmtime(&t);
std::stringstream ss;
ss << std::put_time(gmt, "%Y-%m-%d %H:%M:%S.");
auto tp_secs = std::chrono::system_clock::time_point{}
+ std::chrono::seconds(t);
auto usecs = std::chrono::duration_cast<std::chrono::microseconds>(
tp - tp_secs);
ss << std::setw(6) << std::setfill('0') << usecs.count();
return ss.str();
}
int main(void)
{
auto now = std::chrono::system_clock::now();
auto local_now = to_local(now);
cout << to_log_string(now) << endl;
cout << to_iso_string(local_now) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment