C++ adding days to a date example

 #include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;
class Date
{
    int dd;
    int mm;
    int yyyy;
    string sdate;
    int setdate()
    {
        ostringstream strdt;
        char dsep = '/';
        strdt<<setw(2)<<setfill('0')<<dd<<dsep<<setw(2)<<setfill('0')<<mm<<dsep<<setw(4)<<setfill('0')<<yyyy;
        sdate = strdt.str();
        return 0;
    }
    int leapyear()
    {
        return (yyyy % 4 == 0 ? 29 : 28);
    }
    int mdays()
    {
        int days[]={31,leapyear(),31,30,31,30,31,31,30,31,30,31};
        return days[mm-1];
    }
public:
    Date():dd(1), mm(1), yyyy(2000)
    {
        setdate();
    }
    Date(int d, int m, int y):dd(d), mm(m), yyyy(y)
    {
        setdate();
    }
    int getdate()
    {
        cout<<"Enter year: "; cin>>yyyy;
        if(yyyy < 1970) yyyy = 1970;
        cout<<"Enter month: "; cin>>mm;
        cout<<"Enter date: "; cin>>dd;
        cout<<"Entered date: ";
        setdate();
        printdate();
        return 0;
    }
    int printdate()
    {
        cout<<sdate<<endl;
        return 0;
    }
    Date operator+(int days)
    {
        dd += days;
        while(dd > mdays())
        {
            dd -= mdays();
            mm++;
            if(mm>12)
            {
                mm = 1;
                yyyy++;
            }
        }
        cout<<"New date: " << sdate << " + " << days << " = ";
        setdate();
        printdate();
        return *this;
    }
};


int main()
{
    cout<<"All dates are in dd/mm/yyyy format. Year > 1970."<<endl;
    Date dt;
    int adddt;
    dt.getdate();
    cout<<"Enter days to add: ";
    cin>>adddt;
    dt+adddt;
}

Comments

Popular Posts