Skip to content

Instantly share code, notes, and snippets.

@jhjin
Created September 19, 2016 04:01
Show Gist options
  • Save jhjin/02e4d91e4cc8531279823873d020b917 to your computer and use it in GitHub Desktop.
Save jhjin/02e4d91e4cc8531279823873d020b917 to your computer and use it in GitHub Desktop.
Timestamp conversion
// 2016-08-26T21:10:13.167Z -> 1472245813167
namespace bpt = boost::posix_time;
uint64_t ISOdate2ms_boost(const std::string timestamp_) {
std::string timestamp = timestamp_;
if (timestamp[10] == 'T') timestamp[10] = ' ';
if (timestamp[timestamp.size()-1] == 'Z') timestamp.resize(timestamp.size()-1);
bpt::ptime epoch = bpt::time_from_string("1970-01-01 00:00:00.000");
bpt::ptime birthdate = bpt::time_from_string(timestamp);
bpt::time_duration const diff = birthdate - epoch;
uint64_t timestamp_numeric = diff.total_milliseconds();
return timestamp_numeric;
}
// 2016-08-26T21:10:13.167Z -> 1472245813167
uint64_t ISOdate2ms(const std::string timestamp_iso) {
std::tm t; int msec;
sscanf(timestamp_iso.c_str(), "%d-%d-%dT%d:%d:%d.%dZ",
&t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &msec);
t.tm_year -= 1900;
t.tm_mon -= 1;
return static_cast<uint64_t>(timegm(&t))*1000 + msec;
}
// 1472245813167 -> 2016-08-26T21:10:13.167Z
std::string ms2ISOdate(uint64_t timestamp_ms) {
time_t t_s = static_cast<time_t>(timestamp_ms / 1000);
time_t t_ms = static_cast<time_t>(timestamp_ms % 1000);
char t_sss[30];
strftime(t_sss, sizeof(t_sss), "%Y-%m-%dT%H:%M:%S.", gmtime(&t_s));
return static_cast<std::ostringstream&>
(std::ostringstream() << t_sss << t_ms << "Z").str();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment