Library contents

C strftime

strftime formats the fields of a struct tm into a caller-supplied character buffer using a date or time pattern.

A simple example

strftime

  1. Start with January 2, 2024
  2. Do this Format as year-month-day
  3. Result 2024-01-02
Formatting changes how the date is written while keeping the same calendar day.

Syntax

C syntax
strftime(text, sizeof text, "%Y-%m-%d", &date)
Run this example in C

Save the program as lesson.c. Use C17 and a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Format a calendar date for a report

An office prints dates on reports that people will compare across computers. Assemble the display from the date fields and the intended format so the reader can interpret each component consistently.

Result2024-02-29
lesson.c
#include <stdio.h>
#include <time.h>

int main(void) {
    struct tm date = {.tm_year = 2024 - 1900, .tm_mon = 1, .tm_mday = 29};
    char text[32];
    if (strftime(text, sizeof text, "%Y-%m-%d", &date) == 0) return 1;
    puts(text);
    return 0;
}
Output
2024-02-29

tm_year counts years since 1900 and tm_mon starts at zero. A zero return for this nonempty format means the result did not fit.

Open Group function reference for strftime

Advertisements

Name a concert recording

The school archive sorts dates in file names. Render the already validated date as year-month-day, using two digits for both month and day.

Given7 March 2026
Worked result2026-03-07

Label an exhibition proof

A printer needs a date stamp that sorts correctly in a list. Render the already validated date as year-month-day, using two digits for both month and day.

Given2 November 2027
Worked result2027-11-02