Our Feeds

Saturday, 19 July 2014

Ajith KP

Program to calculate Days between two dates in C++

          This question is very basic and confusing for beginners. Calculate the days between two dates is bit easy if you think deeply.



          Calculating Days : Algorithm

         
          If day2 - day1 <= -1 :

                    days = daysOfMonth(month1)-day1+day2;

          Else:

                    days = day2-day1;

          Calculating Months : Algorithm:

       
          If day2 - day1 <= -1:

                    If month2 - month1 <= -1:

                              months = 12+month2-month1-1;


                    Else:

                              months = month2-month1-1;

          Else:

                    If month2 - month1 <= -1:

                              months = 12+month2-month1;

                    else:

                              months = month2-month1;


          Calculating Years : Algorithm


          If month2 - month1 <= -1:

                    years = year2-year1-1;

          Else:

                    years = year2-year1;

          Source Code


/*
    [][][]
    [][][]
    [][][]
    [][][]  TerminalCoders.Blogspot.de
    [][][]
    [][][]
    [][][]
*/
#include <iostream>
using namespace std;
class date
{
    public:
        int day, month, year;
        void read()
        {
            cout<<"Enter date: ";
            cin>>day>>month>>year;
        }
        date operator -(date);
        int daysOf(int m, int y)
        {
            int days=0;
            if(m==1||m==3||m==5||m==7||m==8||m==10||m==12)
            {
                days=31;
            }
            else if(m==2 && y%4==0 && !(y % 100 == 0))
            {
                days = 29;
            }
            else if(m==2)
            {
                days = 28;
            }
            else
            {
                days = 30;
            }
            return days;
        }
};
date date::operator -(date d)
{
    date df;
    int days    = daysOf(month, year);
    df.day      = ((-1>=d.day-day)?days-day+d.day:d.day-day);
    df.month    = ((-1>=d.day-day)?(-1>=d.month-month?12+d.month-month-1:d.month-month-1):(-1>=d.month-month?12+d.month-month:d.month-month));
    df.year     = ((-1>=d.month-month)?d.year-year-1:d.year-year);
    return df;
}

int main()
{
    date d1, d2, d3;
    d1.read();
    d2.read();
    d3 = d1 - d2;
    cout<<"Days between are: "<<d3.day<<" Days : "<<d3.month<<" Months : "<<d3.year<<" Year";
    cin.get();
    return 0;
}