Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

strftime — formatting dates and times

strftime from <time.h> formats a struct tm into a buffer. The format controls the date and time representation; reserve space for the terminating null character.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <time.h>
size_t strftime(char * restrict s, size_t maxsize,
                const char * restrict format,
                const struct tm * restrict timeptr);

strftime writes a formatted struct tm value into s. format contains text and conversion specifiers: %Y means year, %m month, %d day, and %% a literal %. LC_TIME settings affect locale-dependent representations.

maxsize is the buffer capacity, including \0. The return value counts written bytes excluding \0. If the buffer is too small, the function returns zero; do not treat its contents as a valid string. A successful empty result also returns zero.

The fields used must contain valid values: tm_year counts years since 1900, and tm_mon counts months from zero. Overlapping copy regions and unsupported conversion specifiers cause undefined behavior.

Examples

#include <stdio.h>
#include <time.h>

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

Result

2024-02-29

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources