码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 求两日期间相隔天数

时间:2015-06-01 09:44:35      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:日期

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

struct Date{
    int year;
    int month;
    int day;

    Date(int y = 0, int m = 0, int d = 0):
        year(y), month(m), day(d) {}

    Date & readIn() {
        cin >> year >> month >> day;
        return *this;
    }

    void swap(Date & rhs) {
        Date t(*this);
        *this = rhs;
        rhs = t;
    }

};

bool is_leap(int year) {
    return (year % 400)|| (year % 4 && year % 100);
}

bool operator < (const Date & lhs, const Date & rhs) {
    return (lhs.year < rhs.year) ||
            (lhs.year == rhs.year) && (lhs.month < rhs.month) ||
            (lhs.year == rhs.year) && (lhs.month == rhs.month && lhs.day < rhs.day);
}

int days_of_month(int year,int month) {
    switch(month) {
    case 1: case 3: case 5:case 7:
    case 8: case 10: case 12:
        return 31;
    case 2:
        return is_leap(year) ? 29: 28;

    case 4: case 6: case 9: case 11:
        return 30;
    default:
        return -1;
    }
}

int day_diff(Date lhs, Date rhs) {
<span style="white-space:pre">	</span>//通过不断用其中一个向另一个逼近来求相差天数
    int flag = 1;
    if(rhs < lhs) {
        swap(lhs, rhs);
        flag = -1;
    }

    int day_shf = 0;
    if(lhs.day < rhs.day) {
        day_shf += rhs.day - lhs.day;
        rhs.day = lhs.day;
    }
    if(lhs.day > rhs.day) {
        day_shf -= lhs.day - rhs.day;
        lhs.day = rhs.day;
    }

    while(lhs.month < rhs.month) {
        day_shf += days_of_month(lhs.year ,lhs.month);
        ++lhs.month;
    }
    while(lhs.month > rhs.month) {
        day_shf -= days_of_month(rhs.year ,rhs.month);
        ++rhs.month;
    }
<span style="white-space:pre">	</span>//两个日期始终以相互为界,故日期大小关系不可能改变
    while(lhs.year < rhs.year) {
        day_shf += is_leap(lhs.year) ? 366: 365;
        ++lhs.year;
    }

    return day_shf*flag;
}


int main()
{
    Date d1, d2;
    while(true) {
        d1.readIn(); d2.readIn();
        cout << day_diff(d1, d2) << endl;
    }
    return 0;
}

C++ 求两日期间相隔天数

标签:日期

原文地址:http://blog.csdn.net/qq_21555605/article/details/46293881

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!