avatar
fireworks99
keep hungry keep foolish

日期模拟

时常遇到计算两年间有多少天的日期模拟题,在这里整理一下模板

cal_first_year(int y, int m, int d)今天(包括在内)到年底的天数

cal_last_year(int y, int m, int d)年初至今(包括在内)的天数

cal_only_one_year(5个形参)同年内两日期间天数(闭区间)

#include <cstdio>
#include <iostream>
using namespace std;

int num[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

bool judge(int y)
{
    if((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
        return 1;
    return 0;
}

int cal_first_year(int y, int m, int d)///including this day
{
    int ans = 0;
    for(int i = m + 1; i <= 12; ++i)
        ans += num[i];
    ans += num[m] - d + 1;
    if(judge(y) && ((m == 1) || (m == 2 && d <= 29)) )
            ans ++;
    return ans;
}

int cal_last_year(int y, int m, int d)
{
    int ans = 0;
    for(int i = 1; i <= m - 1; ++i)
        ans += num[i];
    ans += d;
    if(judge(y) && (m > 2))
            ans ++;
    return ans;
}

int cal_only_one_year(int y, int am, int ad, int bm, int bd)
{
    int ans = 0;
    for(int i = am + 1; i <= bm - 1; ++i)
        ans += num[i];
    if(am == bm)
        ans += bd - ad + 1;
    else
        ans += num[am] - ad + 1 + bd;
    if(judge(y) && ((am == 1) || (am == 2 && ad <= 29)) 
       && ((bm == 2 && bd == 29) || (bm > 2)))
        ans++;
    return ans;
}


int main()
{
    cout << cal_only_one_year(2018, 1, 1, 2, 2);
    return 0;
}
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy