C mktime
Let the local calendar normalize an out-of-range day of the month.
A simple example
mktime
- Start with 2024-01-31
- Do this Add one calendar day
- Result 2024-02-01
Syntax
mktime(&arrival)
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonCalculate a delivery date across leap day
A reservation spans the end of February in a leap year. The booking system must use actual calendar days so that the extra day appears in the schedule or stay length.
#include <time.h>
#include <stdio.h>
int main(void) {
struct tm arrival = {0};
arrival.tm_year = 2024 - 1900;
arrival.tm_mon = 2 - 1;
arrival.tm_mday = 28 + 2;
arrival.tm_hour = 12;
arrival.tm_isdst = -1;
if (mktime(&arrival) == (time_t)-1) return 1;
char date[16];
if (strftime(date, sizeof date, "%Y-%m-%d", &arrival) == 0) return 1;
puts(date);
return 0;
}
2024-03-01
February 28 plus two calendar days lands on March 1 in the leap year 2024. mktime writes the normalized fields back into the structure.
Return a borrowed microscope
A school lends a microscope two days before the end of February in a leap year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?
Send a year-end reminder
A gallery schedules its reminder one day after the final day of the year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?
What to watch for
The month starts at zero and the year counts from 1900. This example uses local noon for a civil delivery date.