Open In App

ctime() Function in C/C++

The ctime() function is define in the time.h header file. The ctime() function returns the string representing the localtime based on the argument timer.

Syntax:



char *ctime(const time_t *timer)

Parameters: This function accepts single parameter time_ptr. It is used to set time_t object that contains a time value.

Return Value: This function returns a string that contains the date and time which is in human readable form.



Example:

Www Mmm dd hh:mm:ss yyyy

Time Complexity: O(1)
Auxiliary Space: O(1)

Note: The description of results are given below:

Example:




#include <iostream>
#include <ctime>
 
 
int main() {
    // create a time_t object representing 1 hour from now
    time_t one_hour_from_now = time(0) + 3600;
 
    // convert one_hour_from_now to string form
    char* dt = ctime(&one_hour_from_now);
 
    // print the date and time
    std::cout << "One hour from now, the date and time will be: " << dt << std::endl;
 
    return 0;
}




// 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, the date and time will be: Thu Apr 13 09:01:46 2023

Article Tags :