【问题标题】:Converting time string to seconds in C++ issues在 C++ 问题中将时间字符串转换为秒
【发布时间】:2020-12-21 16:25:37
【问题描述】:

我正在运行嵌入式 Linux 的嵌入式 ARM 设备上编写 C++ 应用程序。

我正在尝试将日期和时间字符串转换为秒,以秒为单位从当前时间中减去它,并在经过的秒数大于某个数字时采取行动。

一些应该很容易实现的东西被证明很棘手,我不知道为什么。

我计算的时间差结果是一个很大的数字,而实际上它应该是一个很小的数字。请参阅我的以下代码。我正在手动硬编码时间和日期字符串以进行测试。

std::string       timestr = "2020-12-21T16:07:00";
struct tm         t = {0};

sscanf(timestr.c_str(), "%04d-%02d-%02dT%02d:%02d:%02d",
           &t.tm_year, &t.tm_mon,  &t.tm_mday,
           &t.tm_hour, &t.tm_min, &t.tm_sec);

t.tm_year -= 1900;   // This is required because my year should be the number of years since 1900

auto tp    = std::chrono::system_clock::from_time_t(std::mktime(&t));
auto now   = std::chrono::system_clock::now();

auto now_s = std::chrono::time_point_cast<std::chrono::seconds>(now);
auto tp_s = std::chrono::time_point_cast<std::chrono::seconds>(tp);

std::chrono::duration<double> diff = now-tp;  // Huge number

auto elapsed = now_s - tp_s;   // This value is massive and not as expected when printed out

【问题讨论】:

  • 你认为now - tp会用什么单位表示?为什么?你需要std::duration_cast()它到正确的单位,而你没有。
  • 这能回答你的问题吗? How to calculate a time difference in C++
  • @underscore_d 我已经修改了我的问题。我正在使用 std::chrono::time_point_cast 并且仍然得到错误的值。
  • 它仍然是“巨大的”,还是只是“错误的”?在这两种情况下,tpnow 和“巨大”和/或“错误”结果的值是多少?不是很清楚。
  • @NathanPierson 我得到了现在和几分钟前的时差。例如,如果是 2 分钟,我希望 120 秒

标签: c++ datetime chrono mktime system-clock


【解决方案1】:

对于那些感兴趣的人,我解决了这个问题。

我们不仅应该在调用std::mktime(&amp;t)之前从年数中减去1900。

t.tm_year -= 1900;

但也必须从月数中减去 1 t.tm_mon -= 1

月份的编号是从 0 到 11,而不是像我们预期的那样从 1 到 12。

这解释了为什么秒数有很大差异。

【讨论】:

    猜你喜欢
    • 2011-07-04
    • 2013-02-17
    • 2021-04-13
    • 2012-05-26
    • 2011-07-11
    • 1970-01-01
    • 2022-01-16
    • 2016-10-02
    • 1970-01-01
    相关资源
    最近更新 更多