如何从 struct tm 中减去一天但确保完整性?

How to subtract a day from struct tm but ensuring integrity?

如何同时从 struct tm 中减去一天以确保新日期有效。

例如,

struct tm time = {};

time.tm_year = year - 1900;

time.tm_mon = month - 1;

time.tm_mday = day;

天 = 1,月 = 9,年 = 2014。

所以,如果我现在减去一天time.tm_mday = 0,这是无效的。
但是我不能只将 tm_mday 设置为 31 并将月份减少 1,因为我不知道在运行时场景中上个月有多少天。

我使用了这里的代码:Algorithm to add or subtract days from a date? 正如@tenfour 在上面的评论中所建议的那样。

在此处添加我的代码以供下一个寻找此代码的人快速参考。

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);
}