所以假设我把tm的时间定在23: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并说明这一点,但是是否有更有效的方法来获得合适的时间呢?
发布于 2019-01-24 08:29:12
是的,您可以使用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。
发布于 2019-01-24 09:05:18
下面是另一种使用霍华德·辛纳特的日期库的方法,它正在进入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 %T\n", anotherTp);如果希望通过用户界面公开对时间点的操作,编译时构造23h、5min等当然不可用。这些文字构造了std::chrono::duration对象,因此需要一种机制将用户输入转换为等效实例。
https://stackoverflow.com/questions/54341997
复制相似问题