visual如何在C++中比较两个日期

visual How to Compare two dates in C++?

本文关键字:两个 日期 比较 C++ visual      更新时间:2023-10-16

你能告诉我是否有办法找到自过去一天以来花费的天数吗(请查看下面的代码)。如果我有一个包含2009年某一天的字符串,我如何将其与当前日期进行比较并显示它已经过去了多少天?

#include <time.h>
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
int main ()
{
   string olday = "05 14 2009";
   const int MAXLEN = 80;
   char newday[MAXLEN];
   time_t t = time(0);
   strftime(newday, MAXLEN, "%m %d %Y", localtime(&t));
   cout <<"Current day is: "<<newday << 'n';
   cout <<"Days spent since olday: "<<???? << 'n';
   return 0;
}

Microsoft visual studio 2010 c++控制台

您可以使用difftime。

http://www.cplusplus.com/reference/clibrary/ctime/difftime/

由于它以秒为单位给出差异,因此很容易转换为天、月等。

首先需要将olday字符串转换为更可用的字符串。执行此操作的方法是创建一个struct tm并填充值。然后将结构tm转换为具有mktime()的time_t,并使用具有两个time_t值的difftime()。并将秒转换为天。

//create a local tm struct
struct tm old_day ;
//since it's a local, zero it out
memset(&old_day, 0, sizeof(struct tm)) ;
//fill in the fields 
old_day.tm_year = 109 ; //years past 1900
old_day.tm_mon = 4 ;//0-indexed
//convert to a time_t
time_t t_old = mktime(&old_day) ;