【C++】计算两个日期之间的差

  • Post author:
  • Post category:其他


rt

代码如下

#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
bool judge(int x) {
    if((x%4==0&&x%100!=0)||x%400==0) return true;
    else return false;
}
int sum(int x1,int x2,int x3,int d1) {
    switch(x2-1) {
        case 11:d1+=30;
        case 10:d1+=31;
        case  9:d1+=30;
        case  8:d1+=31;
        case  7:d1+=31;
        case  6:d1+=30;
        case  5:d1+=31;
        case  4:d1+=30;
        case  3:d1+=31;
        case  2:d1+=28;
        case  1:d1+=31;
        case  0:d1+=x3;
    }
    if(judge(x1)) {
        if(x2>=3) d1+=1;
    }
    return d1;
}
int main() {
    int x1,x2,x3,d1=0;
    int y1,y2,y3,d2=0;
    cin>>x1>>x2>>x3;
    cin>>y1>>y2>>y3;
    d1=sum(x1,x2,x3,d1);
    d2=sum(y1,y2,y3,d2);
    if(x1<y1) {
        int ans=d2;
        if(judge(x1)) ans+=366-d1;
        else ans+=365-d1;
        for(int i=x1+1;i<y1;i++) {
            if(judge(i)) ans+=366;
            else ans+=365;
        }
        cout<<ans;
        return 0;
    }
    else if(x1==y1) {
        cout<<abs(d1-d2);
        return 0;
    }
    else {
        swap(x1,y1);
        swap(d1,d2);
        int ans=d2;
        if(judge(x1)) ans+=366-d1;
        else ans+=365-d1;
        for(int i=x1+1;i<y1;i++) {
            if(judge(i)) ans+=366;
            else ans+=365;
        }
        cout<<ans;
        return 0;
    }
    return 0;
}



版权声明:本文为qq_44343213原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。