Date: 1998jan20
Update: 2026jul28
Language: C/C++
Q. C/C++: When is tomorrow?
A. Sometimes C/C++ is so nice. Say you want to find
tomorrow's date. Do you need to make a table holding
the number of days in each month - and what about leap years?
Nope, this fairly simple code does the trick:
#include <time.h>
#include <stdio.h>
void Today(int &year, int &month, int &day) {
time_t now;
struct tm here;
now = time(NULL); // Get the current time
localtime_r(&now, &here);
year = here.tm_year + 1900;
month = here.tm_mon + 1;
day = here.tm_mday;
}
const time_t SECONDS_PER_DAY = 60 * 60 * 24;
// Returns the date of tomorrow
void Tomorrow(int &year, int &month, int &day) {
time_t now;
struct tm here;
now = time(NULL); // Get the current time
localtime_r(&now, &here);
here.tm_hour = 12; // Set to noon to handle daylight savings - important
here.tm_min = here.tm_sec = 0;
now = mktime(&here) + SECONDS_PER_DAY; // The key line
localtime_r(&now, &here);
year = here.tm_year + 1900;
month = here.tm_mon + 1;
day = here.tm_mday;
}
int main() {
{
int year, month, day;
Today(year, month, day);
printf(" Today is %04d-%02d-%02d\n", year, month, day);
}
{
int year, month, day;
Tomorrow(year, month, day);
printf("Tomorrow is %04d-%02d-%02d\n", year, month, day);
}
}
Outputs:
Today is 2026-07-28
Tomorrow is 2026-07-29