5.4 ctime()

View Categories

5.4 ctime()

2 min read

Overview #

The ctime() function converts a calendar time stored as a time_t value into a human-readable date and time string.

The returned string is formatted in the local time zone and includes the day of the week, month, day, time, year, and a newline character.

Header File #

#include <time.h>

Man Pages #

man 3 ctime

Function Prototype #

char *ctime(const time_t *timer);

Parameters #

Parameter Description
timer Pointer to a time_t object containing the calendar time to be converted.

Return Value #

On success, ctime() returns a pointer to a null-terminated character string representing the date and time.

On failure, it returns:

NULL

Return Format #

The returned string has the following format:

Www Mmm dd hh:mm:ss yyyy\n

Example:

Sun Jul 27 15:45:32 2026

Examples #

Example 1 – Convert Current Time to a Readable String #

main.c #

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

int main(void)
{
    time_t current_time;

    current_time = time(NULL);

    printf("%s", ctime(&current_time));

    return 0;
}

Output #

Sun Jul 27 15:45:32 2026

The output will be different on your system.

Explanation #

current_time = time(NULL);

Obtains the current calendar time.

ctime(&current_time);

Converts the time_t value into a human-readable string.

printf("%s", ctime(&current_time));

Displays the formatted date and time.

Examples #

Example 2 – Store the Returned String #

main.c #

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

int main(void)
{
    time_t current_time;
    char *date_time;

    current_time = time(NULL);

    date_time = ctime(&current_time);

    printf("Current Date and Time: %s", date_time);

    return 0;
}

Output #

Current Date and Time: Sun Jul 27 15:45:32 2026

The output will be different on your system.

Explanation #

char *date_time;

Declares a character pointer to store the address of the formatted string.

date_time = ctime(&current_time);

Stores the pointer returned by ctime().

printf("Current Date and Time: %s", date_time);

Displays the formatted date and time.

Notes #

  • ctime() converts a time_t value into a human-readable string.
  • The returned string is represented in the local time zone.
  • The returned string automatically includes a newline (\n) before the null terminator.
  • The returned pointer refers to statically allocated memory managed by the C library.
  • Each call to ctime() may overwrite the string returned by a previous call.
  • Do not modify or free the returned string.

Related Functions #

  • time()
  • localtime()
  • gmtime()
  • asctime()
  • strftime()

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *