如何从structtm中减去一天,同时确保完整性

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

本文关键字:确保 完整性 一天 structtm      更新时间:2023-10-16

如何在确保新日期有效的同时从structtm中减去一天。

例如,

struct tm time = {};
time.tm_year = year - 1900;
time.tm_mon = month - 1;
time.tm_mday = day;

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

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

我使用了这里的代码:从日期中添加或减去天数的算法?正如@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);
}