Home »
C programs »
C advance programs
C program to get the current date and time using the ctime() function
Here, we are going to learn how to get the current date and time using the ctime() function in C programming language?
Submitted by Nidhi, on July 22, 2021
ctime() Function
The ctime() is a library function which is defined in <time.h> header file, it is used to return the current time in string format based on the argument time.
Here, we will get the current date and time using the ctime() function based on a specified timer argument.
Get the current date and time using the ctime() function using C program
The source code to get the current date and time using the ctime() function is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to get current date and time
// using ctime() function
#include <stdio.h>
#include <time.h>
int main()
{
time_t tm;
char* curDateTime;
time(&tm);
curDateTime = ctime(&tm);
printf("Current Date and Time is: %s", curDateTime);
return (0);
}
Output
Current Date and Time is: Thu Jul 22 21:53:03 2021
Explanation
In the main() function, we created a tm variable of structure time_t and initialize tm time using time() function. Then we got the current date and time using the ctime() function. The ctime() function returns the date-time in string format. After that, we printed the result on the console screen.
C Advance Programs »