0

How would one subtract a day from struct tm at athe same time ensuring the new date is valid.

For example,

struct tm time = {};

time.tm_year = year - 1900;

time.tm_mon = month - 1;

time.tm_mday = day;

with day = 1, month = 9, and year = 2014.

So, if I now subtract a day time.tm_mday = 0, which is invalid.
But I can't just set the tm_mday to 31 and reduce the month by 1 as I don't know how many days are there in the previous month in a runtime scenario.

user2822838
  • 337
  • 1
  • 3
  • 13
  • 5
    Don't try to write this yourself. Use std functions like this: http://stackoverflow.com/a/2344845/402169 – tenfour Feb 05 '15 at 16:46
  • while I agree with @tenfour you would just have to check that the day is greater than one, if not then subtract 1 from the month and set the day to the last day of the previous month. There aren't the same number of days each month and the fact that you would have to consider leap years as well it is much easier to go the route tenfour suggests. – mgrenier Feb 05 '15 at 16:56

1 Answers1

1

I have used the code from here: Algorithm to add or subtract days from a date? as suggested by @tenfour in comments above.

Adding my code here for quick reference for who ever is looking for this next.

struct tm time = {};

time.tm_year = year - 1900;

time.tm_mon = month - 1;

time.tm_mday = day;


if(subtractDay)
{

   AddDays(&time, -1);
}

...................

void AddDays(struct tm* dateAndTime, const int daysToAdd) const
{
    const time_t oneDay = 24 * 60 * 60;

     // Seconds since start of epoch --> 01/01/1970 at 00:00hrs
    time_t date_seconds = mktime(dateAndTime) + (daysToAdd * oneDay);

    *dateAndTime = *localtime(&date_seconds);
}
Community
  • 1
  • 1
user2822838
  • 337
  • 1
  • 3
  • 13