[英]How to Compare two dates in C++?
您能告诉我是否有一种方法可以找到过去一天以来的工作天数(请看下面的代码)。 如果我在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
并填写值。 然后使用mktime()
将struct tm转换为time_t,并将difftime()
与两个time_t
值一起使用。 并从几秒钟转换为几天。
//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) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.