C + + to find days apart between two dates

Source: Internet
Author: User

#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 >> ye        AR >> month >> day;    return *this;        } void Swap (date & RHS) {date T (*this);        *this = RHS;    RHS = t; }};bool is_leap (int year) {return (year% 400) | | (Year% of 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>//by constantly using one of them to another approximation to find the difference in number of days 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>//two dates are always bounded by each other, so date size relationships cannot change 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 + + to find days between two dates

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.