Library contents

C mktime

Let the local calendar normalize an out-of-range day of the month.

A simple example

mktime

  1. Start with 2024-01-31
  2. Do this Add one calendar day
  3. Result 2024-02-01
January ends on day 31. The next day starts a new month.

Syntax

C 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
./lesson

Calculate 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.

From the programstruct tm arrival = {0}
Result2024-03-01
lesson.c
#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;
}
Output
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.

Advertisements

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?

Given28 February 2024 + 2 days
Worked result2024-03-01

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?

Given31 December 2026 + 1 day
Worked result2027-01-01

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.

Documentation for mktime