给两个日期格式为x'x'x'x/xx/xx的时间,计算出两个日期的差值,借鉴了一个博客的代码,原地址搜不到了。
#include "iostream"
#include "string"
#include <stdlib.h>
using namespace std;
bool IsLeap(int year)
{
return (year % 4 ==0 || year % 400 ==0) && (year % 100 !=0);
}
bool timeDifference(string str,int &years,int &months,int &days){
string s1,s2,s3;
s1 = str.substr(0,4);
s2 = str.substr(5,2);
s3 = str.substr(8,2);
years = atoi(s1.c_str());
months = atoi(s2.c_str());
days = atoi(s3.c_str());
int DAY[12]={31,28,31,30,31,30,31,31,30,31,30,31};
if(IsLeap(years)){
DAY[1] = 29;
}
bool result;
result = years >= 0 && months<=12 && months>0 && days<=DAY[months] && days>0;
return result;
}
int DayInYear(int year, int month, int day)
{
int DAY[12]={31,28,31,30,31,30,31,31,30,31,30,31};
if(IsLeap(year))
DAY[1] = 29;
for(int i=0; i<month - 1; ++i)
{
day += DAY[i];
}
return day;
}
int TimeBetween(string timeone,string timetwo){
int years1,months1,days1;
int years2,months2,days2;
if (!timeDifference(timeone,years1,months1,days1) || !timeDifference(timetwo,years2,months2,days2))
{
return -1;
}
cout<<years1<<" "<<months1<<" "<<days1<<endl;
cout<<years2<<" "<<months2<<" "<<days2<<endl;
if (years1==years2 && months1 ==months2)
{
return days1 > days2 ? days1 - days2 : days2 - days1;
}else if(years1 == years2){
int resultday1;
int resultday2;
resultday1 = DayInYear(years1,months1,days1);
resultday2 = DayInYear(years2,months2,days2);
return resultday1 > resultday2 ? resultday1 - resultday2 :resultday2 - resultday1;
}
else{
if (years1 > years2)
{
swap(years1, years2);
swap(months1, months2);
swap(days1, days2);
}
int remainD1,remainD2,remainD3;
if (IsLeap(years1))
{
remainD1 = 366 - DayInYear(years1,months1,days1);
}
else{
remainD1 = 365 - DayInYear(years1,months1,days1);
}
remainD2 = DayInYear(years2,months2,days2);
remainD3 = 0;
for (int i = years1 +1; i < years2; ++i)
{
if (IsLeap(i))
{
remainD3 += 366;
}else{
remainD3 += 355;
}
}
return remainD3 + remainD2 + remainD1;
}
}
int main(int argc, char const *argv[])
{
string str = "2000/10/10";
int years,months,days;
//bool a = timeDifference(str, years,months,days);
int dayfro = TimeBetween("2015/10/20","2014/11/01");
cout<<dayfro;
return 0;
}