C library - ctime() function



The C library ctime() function returns a string representing the localtime based on the argument timer. It transforms the time by the clock, which represents the time in seconds since the Epoch, into a local time string format.

The returned string has the following format: Www Mmm dd hh:mm:ss yyyy, where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year.

Syntax

Following is the syntax of the C library ctime() function −

char *ctime(const time_t *timer)

Parameters

This function accepts only a single parameter −

  • timer − This is the pointer to a time_t object that contains a calendar time.

Return Value

This function returns a C string containing the date and time information in a human-readable format.

Example 1

Following is the basic C library program to see the demonstration of ctime() function.

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

int main () {
   time_t curtime;

   time(&curtime);

   printf("Current time = %s", ctime(&curtime));

   return(0);
}

Output

On execution of above code, we get the following result −

Current time = Mon Aug 13 08:23:14 2012

Example 2

While printing the date and time it retrieves the current system time(sec − Epoch) using the time() function and to convert the time into string format it uses the function ctime().

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

int main() {
   // Current date/time
   time_t tm = time(NULL);
   // convert into string
   char* st = ctime(&tm);
   printf("Date/Time: %s", st);
   return 0;
}

Output

After executing the code, we get the following result −

Date/Time: Tue May 14 06:50:22 2024

Example 3

Below the C example calculates the local time one hour from now using the time() function and display it in a human-readable format using ctime().

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

int main() {
   // Create a time_t object representing 1 hour from now
   time_t one_hour_from_now = time(NULL) + 3600;

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

   // Print the date and time
   printf("One hour from now, the date and time will be: %s\n", dt);
   return 0;
}

Output

The above code produces the following result −

One hour from now, the date and time will be: Tue May 14 07:23:22 2024
Advertisements