blog, c++,

Timestamp in c++

Jing Chi Jing Chi Follow Aug 05, 2019 · 1 min read
Timestamp in c++
Share this

Sometimes, timestamp is useful and important for a received message, a triggered event or just a print log. How can we get and print timestamp like this 2019-08-06 09:19:25.256 in modern c++?

Get current timestamp

#include <ctime>
#include <chrono>

using namespace std::chrono;


system_clock::time_point tp = system_clock::now();

  • Convert to time_t using system_clock::to_time_t
  • Convert to local time with localtime
  • Calculate the remained milliseconds
time_t tm = system_clock::to_time_t(tp);
struct tm stm = *localtime(&tm);

auto dur = tp.time_since_epoch();
dur -= duration_cast<seconds>(dur);

char timestamp[32] = {0};
snprintf(timestamp, sizeof(timestamp),
    "%04u-%02u-%02u %02u:%02u:%02u.%03lu",
    stm.tm_year + 1900, stm.tm_mon + 1, stm.tm_mday,
    stm.tm_hour, stm.tm_min, stm.tm_sec,
    duration_cast<milliseconds>(dur).count());