使用 std::chrono 的 C++ RFC3339 时间戳(以毫秒为单位)

seb*_*ian 6 c++ std rfc3339 c++-chrono

我正在 C++ 中创建一个RFC3339时间戳,包括毫秒和 UTC 格式,std::chrono如下所示:

#include <chrono>
#include <ctime>
#include <iomanip>

using namespace std;
using namespace std::chrono;

string now_rfc3339() {
  const auto now = system_clock::now();
  const auto millis = duration_cast<milliseconds>(now.time_since_epoch()).count() % 1000;
  const auto c_now = system_clock::to_time_t(now);

  stringstream ss;
  ss << put_time(gmtime(&c_now), "%FT%T") <<
    '.' << setfill('0') << setw(3) << millis << 'Z';
  return ss.str();
}

// output like 2019-01-23T10:18:32.079Z

Run Code Online (Sandbox Code Playgroud)

(原谅s using

有没有更直接的方法来获取毫秒数now%1000以毫秒为单位now到达那里似乎有点麻烦。或者关于如何做到这一点更惯用的任何其他评论?

How*_*ant 2

您也可以通过减法来做到这一点:

string
now_rfc3339()
{
    const auto now_ms = time_point_cast<milliseconds>(system_clock::now());
    const auto now_s = time_point_cast<seconds>(now_ms);
    const auto millis = now_ms - now_s;
    const auto c_now = system_clock::to_time_t(now_s);

    stringstream ss;
    ss << put_time(gmtime(&c_now), "%FT%T")
       << '.' << setfill('0') << setw(3) << millis.count() << 'Z';
    return ss.str();
}
Run Code Online (Sandbox Code Playgroud)

这避免了“神奇数字”1000。

此外,还有Howard Hinnant 的免费、开源、单标头、仅标头日期时间库

string
now_rfc3339()
{
    return date::format("%FT%TZ", time_point_cast<milliseconds>(system_clock::now()));
}
Run Code Online (Sandbox Code Playgroud)

这做同样的事情,但语法更简单。