C Program to Display Current Date and Time

In this program, to get current time and print it in human readable string after converting it into local time we are using two functions defined in time.h header file time() and ctime().


time()
  • Header file : time.h
  • Function prototype : time_t time(time_t *seconds).
  • This function is used to get current calendar system time from system as structure.
  • Returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds.
ctime()
  • Header file : time.h
  • Function prototype : char *ctime(const time_t *timer).
  • This function is used to return string that contains date and time informations.
  • Returns a pointer to a string of the form day month year hours:minutes:seconds year.

C Program to print current date and time in human readable form

This program performs two operations, first it calculates the current epoch time(epoch is the number of seconds elapsed since 1st January 1970 midnight UTC) using time function. Then it converts epoch to a string in the format "day month year hours:minutes:seconds year" like "Fri Oct 17 21:30:57 2014".

#include <time.h>
#include <stdio.h>
 
int main(void) {
    time_t current_time;
    char* c_time_string;
 
    current_time = time(NULL);
 
    if (current_time == ((time_t)-1)) {
        printf("Error in computing current time.");
        return 1;
    }
 
    c_time_string = ctime(&current_time);
 
    if (NULL == c_time_string) {
        printf("Error in conversion of current time.");
        return 1;
    }
 
    printf("Current time is %s", c_time_string);
    return 0;
}
Output
Current time is Fri Oct 17 21:30:57 2014
Related Topics
C program to check whether an alphabet is a vowel or consonant
C program to check a number is palindrome or not
C program to check odd or even numbers
C program to check string is palindrome
C program to check if two strings are anagram
C program to calculate power of a number
C Program to calculate factorial of a number
List of all C programs