【问题标题】:C++ RFC3339 timestamp with milliseconds using std::chrono使用 std::chrono 的 C++ RFC3339 时间戳,以毫秒为单位
【发布时间】:2019-01-23 10:30:20
【问题描述】:

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

#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

(原谅usings)

有没有更直接的方法来获取now 的毫秒数? %1000 now 在毫秒内到达那里似乎有些麻烦。或任何其他 cmet 如何做到这一点更惯用?

【问题讨论】:

    标签: c++ std chrono rfc3339


    【解决方案1】:

    你也可以用减法来做到这一点:

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

    这避免了“幻数”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()));
    }
    

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

    【讨论】:

    • 谢谢霍华德,已经偶然发现了你的日期库,它看起来很有帮助!我会牢记在心,以备不时之需。但是在这个项目中,只有一个地方我需要这种格式,所以我宁愿不包括外部来源。
    猜你喜欢
    • 2012-02-23
    • 2018-01-03
    • 2023-03-11
    • 1970-01-01
    • 2015-06-17
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多