Date arithmetic

Basic types / Date and time

void showDate(const char *name, time_t date) {
    struct tm tm;
    localtime_r(&date, &tm);
    char text[16];
    strftime(text, sizeof text, "%Y-%m-%d", &tm);
    printf("%s is %s\n", name, text);
}

// For the current date take time(nullptr) and localtime_r;
// a fixed date keeps the output the same.
struct tm start = {.tm_year = 2024 - 1900, .tm_mon = 2 - 1,
    .tm_mday = 28, .tm_hour = 12, .tm_isdst = -1};
time_t now = mktime(&start);

// Change a field and let mktime normalize the date.
struct tm tm = start;
tm.tm_mday -= 1;
time_t yesterday = mktime(&tm);
//yesterday is 2024-02-27

tm = start;
tm.tm_mday += 1;
time_t tomorrow = mktime(&tm);
//tomorrow is 2024-02-29, a leap year

tm = start;
tm.tm_mon += 1;
time_t nextMonth = mktime(&tm);
//nextMonth is 2024-03-28

tm = start;
tm.tm_year += 1;
time_t nextYear = mktime(&tm);
//nextYear is 2025-02-28

tm = start;
tm.tm_mday += 100;
time_t in100Days = mktime(&tm);
//in100Days is 2024-06-07

showDate("now", now);
showDate("yesterday", yesterday);
showDate("tomorrow", tomorrow);
showDate("nextMonth", nextMonth);
showDate("nextYear", nextYear);
showDate("in100Days", in100Days);