【问题标题】:How to get difference between two times using date library?如何使用日期库获得两次之间的差异?
【发布时间】:2021-07-02 16:55:03
【问题描述】:

我正在使用date library。我不明白如何以毫秒为单位获取 2 个时间点之间的差异?

date::time_of_day<std::chrono::milliseconds> time1;
date::time_of_day<std::chrono::milliseconds> time2;
// set some time...
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(time2 - time1);
std::cout << diff.count() << " milliseconds" << std::endl;

错误:

'operator-' 不匹配(操作数类型为 'date::time_of_day<:chrono::duration long int std::ratio> >' {aka 'date:: hh_mm_ss<:chrono::duration long int std::ratio> > >'} 和 'date::time_of_day<:chrono::duration long int std::ratio> > >' {aka 'date::hh_mm_ss<:chrono::duration long int std::ratio> > >'})

【问题讨论】:

    标签: c++ date


    【解决方案1】:

    在标准化过程后期,time_of_day 更名为hh_mm_sstime_of_day 名称仍然作为 hh_mm_ss 的类型别名存在于 date 中,作为向后兼容性帮助器。

    hh_mm_ss&lt;milliseconds&gt; 只是一个{hours, minutes, seconds, milliseconds} 数据结构,可以方便地从milliseconds 持续时间中获取“字段”。这对于格式化特别有用。但它作为算术类型(例如减法)并没有那么有用。

    要进行算术运算,最好使用持续时间(例如milliseconds)和时间点(例如sys_time&lt;milliseconds&gt;)。例如:

    auto time1 = sys_days{July/2/2021} + 12h + 15min + 3s + 45ms;
    auto time2 = sys_days{July/2/2021} + 13h + 15min + 4s + 145ms;
    auto diff = time2 - time1;
    cout << diff << '\n';
    

    输出:

    3601100ms
    

    在上面的示例中,time1time2 具有类型 date::sys_time&lt;std::chrono::milliseconds&gt;,它本身就是 std::chrono::time_point&lt;std::chrono::system_clock, std::chrono::milliseconds&gt; 的类型别名。而diff 的类型为std::chrono::milliseconds

    【讨论】:

    • 如何将现有的hh_mm_ss&lt;milliseconds&gt; 变量转换为sys_time&lt;milliseconds&gt;
    • hh_mm_ss&lt;milliseconds&gt; 可以通过显式转换语法转换为 duration millisecondsmilliseconds x{hms};。这将只是hh_mm_ss 中字段的总和。然后,如果您真的想要,可以使用相同的显式转换语法将该持续时间转换为 time_point:sys_time&lt;milliseconds&gt; tp{x};。请注意,在 1970-01-01 00:00:00.000 UTC 之后,此时间点的值将是 x milliseconds(假设 x 为正数)。
    • 要处理“没有日期的时间”,请参阅这篇文章以获取不同的选项:stackoverflow.com/a/64895694/576911
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    相关资源
    最近更新 更多