Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用tm进行时间加减_C++_Time_Time T - Fatal编程技术网

C++ 用tm进行时间加减

C++ 用tm进行时间加减,c++,time,time-t,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语句

假设我在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秒。< /P>
#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;
}
#包括
#包括//put\u时间
#包括
int main(int argc,字符**argv){
std::time\u t=std::time(nullptr);
std::tm=*std::localtime(&t);

std::cout这里有另一种使用的方法,它正在进入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);
#包括
#包括“日期/日期.h”
使用名称空间std::chrono_文本;
//代表今天开始的时间点:
今天自动=日期::楼层(标准::计时::系统时钟::现在();
auto someTp=today+23h;//今天23点
auto-anotherTp=someTp-5min-5s;/…现在应该是不言自明的:)

std::cout Yes您需要“执行一系列if语句来检查ptm是否低于0并对此进行解释”。不要以这种方式操纵时间,始终根据历元时间进行操作,这意味着您可以调整1970年以来的毫秒数,并使用标准函数调用将其转换回HMS,从而使生活变得更加轻松。