C print time – C Program to Print Current Date and Time

  • Write a c program to print 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

C print time: 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”.

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

/*
* C Program to Print current system Date
*/
#include <time.h>
#include <stdio.h>
#include <conio.h>
  
int main(void)
{
    time_t current_time;
    char* c_time_string;
  
    /* Obtain current Epoch time. Epoch is the number of seconds that
     * have elapsed since January 1, 1970 (midnight UTC/GMT) 
     */
    current_time = time(NULL);
  
    if (current_time == ((time_t)-1))
    {
        printf("Error in computing current time.");
        return 1;
    }
  
    /* Convert to local time format. */
    c_time_string = ctime(&current_time);
  
    if (NULL == c_time_string)
    {
        printf("Error in conversion of current time.");
        return 1;
    }
  
    /* Print current Time and Date */
    printf("Current time is %s", c_time_string);
    getch();
    return 0;
}

Program Output

Current time is Fri Oct 17 21:30:57 2014