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

来源:互联网 发布:淘宝自动浏览软件app 编辑:程序博客网 时间:2024/05/18 22:08

参考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;  
}  
0 0
原创粉丝点击