ctime() Function in C/C++

Last Updated : 11 Jul, 2026

The ctime() function in C/C++ converts a time_t value into a human-readable representation of the local date and time. It is declared in the <time.h> header in C and the <ctime> header in C++.

  • Converts a time_t value into a local date-time representation.
  • Declared in <time.h> (C) and <ctime> (C++).
C++
#include <iostream>
#include <ctime>
using namespace std;

int main(){
    time_t currentTime = time(nullptr);

    cout << "Current Local Time: " << ctime(&currentTime);

    return 0;
}

Output
Current Local Time: Sat Jul 11 08:25:28 2026

Syntax

char *ctime(const time_t *timer)

  • Parameters: timer - pointer to a time_t object containing the calendar time to be converted.
  • Return Value: returns a pointer to a null-terminated string containing the local date and time.

Date-Time Format Returned by ctime()

The returned string has the following format:

Www Mmm dd hh:mm:ss yyyy

where:

  • Www - Abbreviated day of the week.
  • Mmm - Abbreviated month name.
  • dd - Day of the month.
  • hh - Hour (24-hour format).
  • mm - Minutes.
  • ss - Seconds.
  • yyyy - Year.

Example

C++
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
    // Current time + 1 hour
    time_t one_hour_from_now = time(nullptr) + 3600;

    // Convert to readable string
    char* dt = ctime(&one_hour_from_now);

    cout << "One hour from now: " << dt;

    return 0;
}
C
// C program to demonstrate
// ctime() function.
#include <stdio.h>
#include <time.h>

int main () {
    time_t curtime;
    
    time(&curtime);
    
    printf("Current time = %s", ctime(&curtime));
    
    return(0);
}

Output
One hour from now: Sat Jul 11 07:58:03 2026

Explanation

  • time(nullptr) returns the current calendar time as a time_t value.
  • Adding 3600 represents one hour (3600 seconds).
  • ctime() converts the time_t value into a readable local date-time string.
  • The returned string includes the day, month, date, time, and year.

Common Uses of ctime()

The ctime() function is commonly used in the following scenarios:

  • Displaying the current local date and time.
  • Converting a time_t value into a human-readable format.
  • Logging timestamps in console or file-based applications.
  • Debugging programs that work with date and time.

Notes

  • ctime() returns a pointer to a statically allocated string that is overwritten by subsequent calls to ctime(), asctime(), or localtime().
  • The returned string includes a newline character ('\n') before the null terminator.
  • ctime() is not thread-safe because it uses internal static storage.
Comment