【问题标题】:How to find difference in time in seconds and nanoseconds between two dates?如何在两个日期之间找到以秒和纳秒为单位的时间差?
【发布时间】:2020-09-29 01:16:03
【问题描述】:

我需要计算 Unix 纪元(UTC 时间 1970 年 1 月 1 日 00:00:00)与用户选择的未来某个日期之间的秒数和纳秒数。

到目前为止,这是我通过其他 Stack Overflow 答案找到的:

// seconds and nanoseconds past epoch
auto now = std::chrono::system_clock::now().time_since_epoch();
auto now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(now);
auto now_sec = std::chrono::duration_cast<std::chrono::seconds>(now);

// output total ns since epoch
qDebug() << now_ns.count() << "ns";
// output total secs since epoch
qDebug() << now_sec.count() << "secs";

auto nano_secs = now_ns.count() - (now_sec.count() * 1000000000);
// output ns minus whole seconds
qDebug() << "nano_secs = " << nano_secs;

使用它,我可以得到我正在寻找的当前日期和时间的结果,但这不是我需要的。假设出于演示目的,未来日期是 2020 年 7 月 1 日 00:00:00 UTC。我该如何计算这个?

【问题讨论】:

  • (now_sec.count() * 1000000000)dont 这样做 - 使用 duration_cast 然后做减法。
  • auto nano_secs = now_ns - now_sec; 在我看来是合理的(根本没有 duration_cast)。

标签: c++ datetime time chrono


【解决方案1】:

在 C++20 中,这看起来像:

using namespace std::chrono;
nanoseconds now_ns = sys_days{July/1/2020}.time_since_epoch();
auto now_sec = duration_cast<seconds>(now_ns);
now_ns -= now_sec;
std::cout << now_sec << ", " << now_ns << '\n';

输出:

1593561600s, 0ns

今天要找到一个可以做到这一点的 C++20 std::lib 将很困难。不过here is a free, open-source preview of C++20 &lt;chrono&gt;.

只需添加#include "date/date.h"using namespace date;,就可以了。

如果您不想使用此第 3 方标头,请使用 here is the algorithm to convert a {y, m, d} triple into a count of days,因为 Unix epoch。事实上,所有sys_days{July/1/2020} 所做的只是在后台调用days_from_civil 并将其放入基于system_clock 的天精度chrono::time_point。从那时起,&lt;chrono&gt; 的 C++11/14 版本完成了所有工作。

上述计算均不依赖于您计算机的本地时区设置。

【讨论】:

    猜你喜欢
    • 2012-09-13
    • 1970-01-01
    • 2012-12-03
    • 2023-04-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 2011-05-20
    相关资源
    最近更新 更多