用 tm 加减时间
Adding and subtracting time with tm
假设我在 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;
}
我的输出:
时间:01/24/19 09:26:46 W. 欧洲标准时间
1000 秒时间:01/24/19 09:43:26 W. 欧洲标准时间
如您所见,时间从09:26:46
到09:43:26
.
这是使用Howard Hinnant的日期库的另一种方法,它正在进入C++2a。
#include <iostream>
#include "date/date.h"
using namespace std::chrono_literals;
// Time point representing the start of today:
auto today = date::floor<date::days>(std::chrono::system_clock::now());
auto someTp = today + 23h; // Today, at 23h00
auto anotherTp = someTp - 5min - 5s; // ... should be self-explanatory now :)
std::cout << date::format("%b-%d-%Y %Tn", anotherTp);
如果要通过用户界面公开时间点的操作,编译时构造23h
、5min
等当然不可用。这些文本构造std::chrono::duration
对象,因此您需要一种机制来将用户输入转换为等效实例。
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 从持续时间构造std::chrono::system_clock::time_point
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 使用简单类型列表实现的指数编译时间.为什么
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在已经使用Git的情况下减少编译时间
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 从文本文件中读取时钟时间和事件时间并进行处理
- 具有未知值时的时间复杂性
- 如何减少花费的时间
- C++在变量给定的指定时间内关闭电脑
- rcpp函数中的清理时间很长
- C++:floor unix时间戳到UTC月份
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 用 tm 加减时间
- C++ 将包含 UTC 日期和时间的字符串转换为 TM 结构
- 正在查找具有tm以外的成员对象的另一个时间结构
- 我如何使用tm结构添加分钟到当前时间