Print current date and time in C
Write a C program to print the current date and time in standard output.
We know that time.h header file contains definitions of functions to get and manipulate date and time information. The following C source code prints the current date and time to the standard output stream using tm structure, which holds calendar date and time broken down into its components.
Following is a simple C implementation to get the current date and time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#include <stdio.h> #include <stdlib.h> #include <time.h> // Print the current date and time in C int main(void) { // variables to store the date and time components int hours, minutes, seconds, day, month, year; // `time_t` is an arithmetic time type time_t now; // Obtain current time // `time()` returns the current time of the system as a `time_t` value time(&now); // Convert to local time format and print to stdout printf("Today is %s", ctime(&now)); // localtime converts a `time_t` value to calendar time and // returns a pointer to a `tm` structure with its members // filled with the corresponding values struct tm *local = localtime(&now); hours = local->tm_hour; // get hours since midnight (0-23) minutes = local->tm_min; // get minutes passed after the hour (0-59) seconds = local->tm_sec; // get seconds passed after a minute (0-59) day = local->tm_mday; // get day of month (1 to 31) month = local->tm_mon + 1; // get month of year (0 to 11) year = local->tm_year + 1900; // get year since 1900 // print local time if (hours < 12) { // before midday printf("Time is %02d:%02d:%02d am\n", hours, minutes, seconds); } else { // after midday printf("Time is %02d:%02d:%02d pm\n", hours - 12, minutes, seconds); } // print the current date printf("Date is: %02d/%02d/%d\n", day, month, year); return 0; } |
Output:
Today is Sun Apr 2 23:23:59 2017
Time is 11:23:59 pm
Date is: 02/04/2017
In C++ 11, we can also use std::chrono::system_clock::now(), which returns a time point representing the current point in time.
That’s all about printing the current date and time in C.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)