c++ - 用tm加减时间

标签 c++ time time-t

假设我将 tm 中的时间设置为 23:00:00

ptm->tm_hour = 23; ptm->tm_min = 0; ptm->tm_sec = 0;

我想允许用户从中减去时间

ptm->tm_hour -= hourinput; ptm->tm_min -= minuteinput; ptm->tm_sec -= secondinput;

如果用户减去 0 小时 5 分 5 秒,而不是显示为 22:54:55,它将显示为 23:-5:-5。

我想我可以做一堆 if 语句来检查 ptm 是否低于 0 并说明这一点,但是有没有更有效的方法来获得正确的时间?

最佳答案

是的,您可以为此使用 std::mktime。它不只是将 std::tm 转换为 std::time_t,如果某些字段超出范围,它还会修复 tm范围。考虑这个例子,我们将当前时间加上 1000 秒。

#include <iostream>
#include <iomanip> // put_time
#include <ctime>

int main(int argc, char **argv) {
    std::time_t t = std::time(nullptr);
    std::tm tm = *std::localtime(&t);
    std::cout << "Time: " << std::put_time(&tm, "%c %Z") << std::endl;
    tm.tm_sec += 1000; // the seconds are now out of range
    //std::cout << "Time in 1000 sec" << std::put_time(&tm, "%c %Z") << std::endl; this would crash!
    std::mktime(&tm); // also returns a time_t, but we don't need that here
    std::cout << "Time in 1000 sec: " << std::put_time(&tm, "%c %Z") << std::endl;
    return 0;
}

我的输出:

Time: 01/24/19 09:26:46 W. Europe Standard Time

Time in 1000 sec: 01/24/19 09:43:26 W. Europe Standard Time

如您所见,时间从 09:26:46 变为 09:43:26

关于c++ - 用tm加减时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54341997/

相关文章:

c++ - 我怎样才能 "unelevate"一个进程

c++ - 两个应用程序如何监听一个端口?

c - struct tm 位于另一个结构体中 - c

mysql - 如何在数据库中存储秒数?

c - 使用 struct tm 打印特定日期和 strftime

c - time_t 类型变量的相等性检查

c++ - 确定类型是否为 C++ 中相同的基础类型的别名

c++ - vector::clear() 花这么多时间?

c - 如何测量 C 中 ARM Cortex-M4 处理器的运行时间?

Java:时间分辨率