Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

ctime — deprecated C23 time function

`ctime(timer)` from `<time.h>` converts the pointed-to `time_t` calendar time to a local-time string and returns the pointer produced by the equivalent of `asctime(localtime(timer))`. In C23 its declaration is `[[deprecated]]`; the function is obsolescent and should be avoided in new code.

Version: C23

Syntax

[[deprecated]] char *ctime(const time_t *timer);

ctime(timer) from <time.h> converts the pointed-to time_t calendar time to a local-time string and returns the pointer produced by the equivalent of asctime(localtime(timer)). In C23 its declaration is [[deprecated]]; the function is obsolescent and should be avoided in new code.

The example passes a zero time_t, checks the pointer, and prints the string length plus whether it ends in a newline. Zero was a valid time on the tested platform; C defines neither its epoch nor its encoding. The 25-character format applies only after successful conversion to a broken-down time with a year from 1000 through 9999. Outside that domain asctime has undefined behavior, so a later NULL check cannot validate an invalid input.

The returned buffer can be overwritten by a later time-conversion call that uses the same object; these functions are not reentrant and need not avoid data races with each other. Access through the pointer after the calling thread exits is UB. New code should use localtime_r with its own struct tm, then strftime into an owned buffer.

Examples

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

int main(void) {
    time_t moment = 0;
    char *text = ctime(&moment);
    if (text == NULL) return 1;
    size_t length = strlen(text);
    printf("%zu %d\n", length, length > 0 && text[length - 1] == '\n');
    return 0;
}

Result

25 1

The example passes a zero `time_t`, checks the pointer, and prints the string length plus whether it ends in a newline. Zero was a valid time on the tested platform; C defines neither its epoch nor its encoding. The 25-character format applies only after successful conversion to a broken-down time with a year from 1000 through 9999. Outside that domain `asctime` has undefined behavior, so a later `NULL` check cannot validate an invalid input.

Sources