C++ RFC3339 时间戳与毫秒使用 std::chrono

标签 c++ std c++-chrono rfc3339

我正在创建一个 RFC3339时间戳,包括毫秒和 UTC,在 C++ 中使用 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

(原谅使用)

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

最佳答案

你也可以用减法来做:

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();
}

这避免了“魔数(Magic Number)”1000。

此外,还有 Howard Hinnant's free, open source, single-header, header-only datetime library :

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

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

关于C++ RFC3339 时间戳与毫秒使用 std::chrono,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54325137/

相关文章:

c++ - 使用预先已知的模式进行内存分配

c++ - std::string.substr 运行时错误

c++ - 如何制作通用精度 ISO 时间戳生成器

c++ - 尝试使用 opencv c++ 绘制简单函数

c++ - CMake 将多个子项目构建到一个目录中

c++ STL容器存储了一个重载operator =的类

c++11 - 如何序列化 std::chrono::分钟

c++ - 如何将 date::year_month_day 转换为 chrono time_point

c++ - 如何在我的构造函数中初始化树节点内的数组?

c++ - std::advance 和 std::next 有什么区别?