日期差值(日期问题)

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <map>
#include <stack>
using namespace std;

int type(int n) {
    // 四年一润 百年不润   四百年又润
    if((n % 4 == 0 && n % 100 != 0) || n % 400 == 0) {
        return 1;
    }
    return 0;
}

int b[2] = {365, 366};
int d[2][13] = {
    0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
    0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};


void setIntFromString(string& s, int& year, int& month, int& day) {
    string sub = s.substr(0, 4); //pos,len
    year = atoi(sub.c_str());
    sub = s.substr(4, 2); //pos,len
    month = atoi(sub.c_str());
    sub = s.substr(6, 2); //pos,len
    day = atoi(sub.c_str());
    return ;
}


int getDays(int year, int month, int day) {
    int days = 0;
    // 注意是小于等于
    for (int i = 1; i < year; i++) {
        days += b[type(i)];
    }
    for (int i = 1; i < month; i++) {
        days += d[type(year)][i];
    }
    days += day;
    return days;
}


int main() {
    string s1;
    string s2;
    int y1, m1, d1;
    int y2, m2, d2;
    cin >> s1 >> s2;
    setIntFromString(s1, y1, m1, d1);
    setIntFromString(s2, y2, m2, d2);
    cout << y1 << " " << m1 << " " << d1 << endl;
    cout << y2 << " " << m2 << " " << d2 << endl;
    /*
    正确写法:
    计算00000000 与20120101的差值
    计算000000 与20150101的差值
    abs两项相减
    */

    int res = getDays(y1, m1, d1) - getDays(y2, m2, d2);
    res = abs(res);
    cout << res << endl;






    /*
    错误写法:
    	//20150602
    	//20160209
    	int days = 0;

    	for (int i = y1; i < y2; i++) {
    		days += b[type(i)];
    	}
    	for (int i = m1; i < m2; i++) {
    		days += d[type(y2)][i];
    	}
    	days += (d2-d1);
    	cout<<days;
    */
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值