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:
- Do not forget to include time.h header file
- Time is in 24 hour format.
- year starts counting from 1900. So, you have to add 1900 to timeinfo->tm_year
- Month starts from 0. (0 for Jan, 1 for Feb and 11 for Dec)
No comments:
Post a Comment