Search This Blog

How to Get Time and Date in C - C Program to Read and Display Time and Date

In this post, we will discuss how to read system time (current time) and date in c. To get system time and date, we use the time.h header file. It contains functions related to time and date. The function time() reads the current time and stores in the variable given as parameter. For example, if we call time(now), then the variable now is assigned the current date and time value. This parameter should be of type time_t. A sample code is:

time_t now;
time ( &now );

Note that we should pass the reference to a variable of type time_t.  But, the value stored by the function time() contains all information including date and time. So, the value appears to be an unintelligible random number. There fore, to extract hours, minutes, seconds, year, month, day of month etc from this value, we should convert into an object of structure struct tm. The function localtime() converts the value for us. This conversion to date and time can be done as follows:


struct tm *timeinfo;
timeinfo = localtime ( &now );

Here, timeinfo  is a variable of type struct tm. Now you can read hours, minutes, seconds, year, month and day of month from this variable timeinfo.

//Declaring vriables
time_t now;
struct tm *timeinfo;
int hour,min,sec,year,month,date;

//reading time and date to 'now'
time(&now);


//converting to struct tm type
timeinfo=localtime(&now);


//reading date and time from the struct variable
hour=timeinfo->tm_hour;
min=timeinfo->tm_min;
sec=timeinfo->tm_sec;
year=timeinfo->tm_year+1900;
month=timeinfo->tm_mon+1;
date=timeinfo->tm_mday;
Note:

  1. Do not forget to include time.h header file
  2. Time is in 24 hour format.
  3. year starts counting from 1900. So, you have to add 1900 to timeinfo->tm_year
  4. Month starts from 0. (0 for Jan, 1 for Feb and 11 for Dec)

No comments: