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
- Start with January 2, 2024
- Do this Format as year-month-day
- Result 2024-01-02
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.
#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;
}
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
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.
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.