Published on

Getting a Millisecond Timestamp and Formatting It as a Date String in C++

Authors

In a program we build at work, I needed to obtain timestamps with millisecond precision, so I wrote a small utility for it using Boost.Chrono.

#include <iomanip>
#define BOOST_CHRONO_VERSION 2
#include <boost/chrono.hpp>

long long TimestampMillseconds()
{
  using namespace boost::chrono;
  return duration_cast<milliseconds>(
      system_clock::now().time_since_epoch()).count();
}

std::string FormatTimestamp(long long timestamp)
{
  using namespace boost::chrono;

  milliseconds ms(timestamp);

  std::stringstream ss;
  ss << time_fmt(timezone::local, "%Y%m%d%H%M%S")
     << system_clock::time_point(ms)
     << std::setfill('0')
     << std::setw(3)
     << (ms - duration_cast<seconds>(ms)).count();

  return ss.str();
}

int main()
{
  long long timestamp = TimestampMillseconds();
  std::cout << timestamp << "\n"
            << FormatTimestamp(timestamp) << "\n";

  return 0;
}

When converting a timestamp to a date string, I found that there was no format specifier for values below milliseconds, so I formatted only the part down to seconds and then appended the millisecond portion by taking the difference. If you want microsecond precision instead, change the template argument to boost::chrono::microseconds in duration_cast.

The output looks like this.

1405692197925
20140718230317925