如何从日期中减去时间

How to subtract time from date

本文关键字:时间 日期      更新时间:2023-10-16

是否有标准的c++时间类有方法来减去日期例如:我想从这样的日期(Jan 1 Mon 2014 00:05)中减去10分钟,得到这样的日期(Dec 31 Sun 2013 23:55)

如果"struct tm"类型有这样的函数就好了

cppreference显示了足够的函数(mktime, localtime)来将struct tm转换为time_ttime_t的计算很明显,因为它是一个整数类型,传统上表示1970年以来的秒数。

我不知道struct tm是否有任何方法,但我认为你应该阅读C++11中可用的chrono。链接

如果你会使用c++ 11,你可以很容易地减去和添加日期:

#include <iostream>
#include <chrono>
#include <ctime>
#include <ratio>
using namespace std;
int main ()
{
  chrono::system_clock::time_point today = chrono::system_clock::now();
  chrono::system_clock::duration dtn (chrono::duration<int,ratio<60,1>>(10));
  time_t t = chrono::system_clock::to_time_t(today-dtn);
  cout << ctime(&t) << endl;
  return 0;
}