【问题标题】:What is the best approach to get a millisecond-rounded timestamp string in Howard Hinnant's Date library?在 Howard Hinnant 的 Date 库中获取毫秒舍入时间戳字符串的最佳方法是什么?
【发布时间】:2020-07-07 10:27:11
【问题描述】:

我有以下代码,使用日期库:

#include "date.h"
#include <iostream>
#include <sstream>

using namespace date;
using namespace std::chrono;

int main()
{
    auto now = system_clock::now();
    std::stringstream ss;
    ss << now;
    std::string nowStr = ss.str();   // I need a string
    std::cout << nowStr << " UTC\n";
}

结果是:

2020-03-26 17:38:24.473372486 UTC

stringstream 是从 now() 返回的 chrono::timepoint 获取字符串的正确方法吗?如果是这样,我如何将这些纳秒四舍五入到毫秒?

【问题讨论】:

    标签: c++ date c++11 time chrono


    【解决方案1】:

    是的,ostringstream 是一个很好的方法。你也可以使用date::format,它返回一个string,但这仍然在内部使用ostringstream

    string s = format("%F %T %Z", now);
    

    使用任何一种技术,您都可以在格式化之前将输入time_point 截断为milliseconds,从而将其截断为milliseconds 输出。您可以选择以下任何一种舍入模式:

    • 向纪元日期舍入:time_point_cast&lt;milliseconds&gt;(now)
    • 向过去转:floor&lt;milliseconds&gt;(now)
    • 面向未来:ceil&lt;milliseconds&gt;(now)
    • 朝最近的方向舍入(甚至在领带上):round&lt;milliseconds&gt;(now)

    -

    string s = format("%F %T %Z", floor<milliseconds>(now));
    
    2020-03-26 17:38:24.473 UTC
    

    在 C++20 中,这将变为:

    string s = format("{:%F %T %Z}", floor<milliseconds>(now));
    

    【讨论】:

      猜你喜欢
      • 2011-05-17
      • 2011-07-05
      • 2010-10-02
      • 2016-06-05
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多