两个日期之间差

给两个日期格式为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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值