您的位置:首页 > 编程语言 > C语言/C++

C++求两个日期之间的相差天数

2015-09-28 16:15 543 查看
参考http://blog.csdn.net/nanhaizhixin/article/details/8349668

#include <stdio.h>

#include <string>

#include <time.h>

using namespace std;

string GetLastNthDate(int n);

time_t FormatTime2(char * szTime)  ;

void main()

{
printf("start!\n");
string timeStr = GetLastNthDate(2);

printf("time:%s", timeStr.c_str());

char time_prev[512] = {0};
sprintf(time_prev,"%s000000","20150905");
char time_curr[512] = {0};
sprintf(time_curr,"%s000000","20150831"); 
time_t time_t_prev = FormatTime2(time_prev);
time_t time_t_curr = FormatTime2(time_curr);
long long days = (time_t_prev-time_t_curr)/86400; //1天=24*60*60秒

printf("days %lld", days);

}

string GetLastNthDate(int n)

{
time_t current_t = time(0);
time_t lastDay_t = time(0);
char lastDay_time[128];

lastDay_t = current_t - 86400*n; //每天差86400秒
strftime( lastDay_time, sizeof(lastDay_time), "%Y%m%d", gmtime(&lastDay_t)); 

return string(lastDay_time);

}

time_t FormatTime2(char * szTime)  

{  
struct tm tm1;  
time_t time1;  

sscanf(szTime, "%4d%2d%2d%2d%2d%2d",      
&tm1.tm_year,   
&tm1.tm_mon,   
&tm1.tm_mday,   
&tm1.tm_hour,   
&tm1.tm_min,  
&tm1.tm_sec);  

tm1.tm_year -= 1900;  
tm1.tm_mon --;  

tm1.tm_isdst=-1;  

time1 = mktime(&tm1);  
return time1;  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 日期