Published on

C++ で milliseconds 単位のタイムスタンプ取得と日付文字列への変換

Authors

会社で作っているプログラムで,タイムスタンプを milliseconds 単位で取得する必要がありプログラムを作りました.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;
}

タイムスタンプから日付文字列に変換するとき,milliseconds 以下を変換する指定子がなかったので,秒以上のみを変換し,milliseconds 以下は差分を出して連結しています.タイムスタンプを microseconds 単位で取得したい場合は,duration_cast のテンプレート引数を boost::chrono::microseconds にします.下記が出力結果です.

1405692197925
20140718230317925