【发布时间】: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 并且仍然得到错误的值。
-
它仍然是“巨大的”,还是只是“错误的”?在这两种情况下,
tp、now和“巨大”和/或“错误”结果的值是多少?不是很清楚。 -
@NathanPierson 我得到了现在和几分钟前的时差。例如,如果是 2 分钟,我希望 120 秒
标签: c++ datetime chrono mktime system-clock