I have been given a date, Which I am taking as an input like (day, month, year): 12, 03, 87
.
Now I need to find out the date after n
days.<
It might be easier to do the math using seconds since the epoch instead of manipulating the date fields directly.
For example, this program prints the date 7 days from now:
#include <stdio.h>
#include <time.h>
main()
{
time_t t;
struct tm *tmp;
time(&t);
/* add a week to today */
t += 7 * 24 * 60 * 60;
tmp = localtime(&t);
printf("%02d/%02d/%02d\n", tmp->tm_mon+1, tmp->tm_mday,
tmp->tm_year % 100);
}
The standard library mktime
function includes a trick to make it easy to add a number of months or days into a given date: you can give it a date such as "45th of February" or "2nd day of the 40th month" and mktime
will normalize it into a proper date. Example:
#include <time.h>
#include <stdio.h>
int main() {
int y = 1980;
int m = 2;
int d = 5;
int skip = 40;
// Represent the date as struct tm.
// The subtractions are necessary for historical reasons.
struct tm t = { 0 };
t.tm_mday = d;
t.tm_mon = m-1;
t.tm_year = y-1900;
// Add 'skip' days to the date.
t.tm_mday += skip;
mktime(&t);
// Print the date in ISO-8601 format.
char buffer[30];
strftime(buffer, 30, "%Y-%m-%d", &t);
puts(buffer);
}
Compared to doing the arithmetic in seconds using time_t
, this approach has the advantage that daylight savings transitions do not cause any problems.