How to add days to date in C++

In the given approach, we use rational brute force method to add given number of days to a given date in C++.

Firstly we write smaller functions to be used in our program like. isleapyear is used to check if a year is leap or not. offsetdays to calculate offset i.e. the number of days elapsed from the beginning of the year(1st january). adddays to add the given number of days in our entered date. revoffsetdays for given a year and number of days passed in it, finds date by storing resulting data into d and m.

In the driver code, we can either ask the user to enter input for date and the number of days to be added or we can directly put that in main function.



Add days to date in C++

The given is a programming approach for the same.

bool isleapyear(int year)  
{  
    if (year % 400 == 0)  
        return true;  
  
    if (year % 100 == 0)  
        return false;  
  
    if (year % 4 == 0)  
        return true;  
    return false;  
}
int offsetdays(int d, int m, int y) 
{ 
    int offset = d; 

    switch(m-1) 
    {
    case 1: 
        offset=offset+ 31; 
    case 2: 
        offset=offset+ 28;
    case 3: 
        offset=offset+ 31; 
    case 4: 
        offset=offset+ 30; 
    case 5: 
        offset=offset+ 31;
    case 6: 
        offset=offset+ 30; 
    case 7: 
        offset=offset+ 31; 
    case 8: 
        offset=offset+ 31;
    case 9: 
        offset=offset+ 30;  
    case 10: 
        offset=offset+ 31;
    case 11: 
        offset=offset+ 30; 
     
    } 

    if (isleapyear(year) && m > 2) 
        offset += 1; 

    return offset; 
}
int montharray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
void revoffsetdays(int offset, int year, int *d, int *m)
 { 
 if (isleapyear(year)) 
{montharray[2] = 29; }
integer i; 
for (i = 1; i <= 12; i++) 
{ 
if (offset <= montharray[i])
 break;

 offset = offset - montharray[i];
 }
 *d = offset; 
*m = i;
 }

 void addDays(int d1, int m1, int year1, int x)
 { int offset1 = offsetdays(d1, m1, year1);
 int remdays = isleapyear(year1)?(366-offset1):(365-offset1); 
// year2 stores result year 
// offset2 stores the number of offset days in result year.
 int year2, offset2;
 if (x <= remdays) 
{ year2 = year1; offset2 = offset1 + x; } 

else 
{
 x -= remdays;
 year2 = year1 + 1;
 int year2days = isleapyear(year2)?366:365;
 while (x >= y2days) { x -= y2days; y2++; y2days = isleapyear(y2)?366:365; }
 offset2 = x; 
} 
int m2, d2;
 revoffsetdays(offset2, year2, &d2, &m2); 
cout <<d2<<":"<< m2 << ":" r; } 

int main()
 { int d=21, m=2, y=2019;
 int x = 369;
 adddays(d, m, year, x);
 return 0; 
}

 

Sample Output:

25:2:2020

Also Read:

Leave a Reply

Your email address will not be published. Required fields are marked *