首页 > 代码库 > 九度题目1096:日期差值

九度题目1096:日期差值

题目描述:

有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天

输入:

有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD

输出:

每组数据输出一行,即日期差值

样例输入:
20110412
20110422
样例输出:
11

#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<stack>
#include<vector>
#include<string.h>
#include<limits.h>
#include<stdlib.h>

#define ABS(x) ((x)>=0?(x):(-(x)))
using namespace std;
static int month[12]={0,31,28,31,30,31,30,31,31,30,31,30};
int days_from(int year)
{
    int y = year/10000;
    int m = (year - y*10000)/100;
    int d = year%100;
    int result = 0;
    int i;
    for(i=1000;i<y;i++)
    {
        if((i%4==0&&i%100!=0)||i%400==0)
            result+=366;
        else
            result+=365;
    }
    for(i=1;i<m;i++)
    {
        if(i==2)
        {
            if((y%4==0&&y%100!=0)||y%400==0)
                result += month[i]+1;
            else
                result += month[i];
        }
        else
            result += month[i];

    }

    return result+d;

}
int main()
{
    freopen("test.in","r",stdin);
    freopen("test.out","w",stdout);
    int year1, year2;
    int days1, days2;
    while(cin>>year1>>year2)
    {
        days1 = days_from(year1); 
        days2 = days_from(year2); 
        cout<<ABS(days1-days2)+1<<endl;
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}


闰年的判断 ((y%4==0&&y%100!=0)||y%400==0)

九度题目1096:日期差值