C Language | Advanced Features | Time Functions - time(), localtime()
Standard C functions can retrieve the computer’s time. Since time is stored as a numeric value, convert it to local calendar time before displaying it as a date.
Handling Time
Time-related functions are declared in time.h. Use time() to retrieve the system time.
time() Function
time_t time(time_t *timer);
time_t is an arithmetic type defined by the implementation. time() stores the result through timer and also returns the same value. Pass NULL when only the return value is needed. On failure, it returns (time_t)-1.
Many systems represent time as seconds elapsed since 1970-01-01 00:00:00 UTC. Use localtime() to convert a time_t value into local calendar fields.
localtime() Function
struct tm *localtime(const time_t *timer);
localtime() returns a pointer to a tm structure.
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of month */
int tm_mon; /* months since January */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday */
int tm_yday; /* days since January 1 */
int tm_isdst; /* daylight saving time flag */
};
tm_mon starts at 0, and tm_year counts from 1900.
Code 1
#include <stdio.h>
#include <time.h>
int main() {
struct tm *date;
const time_t t = time(NULL);
date = localtime(&t);
printf("%d/%d/%d %d:%d:%d\n",
date->tm_year + 1900, date->tm_mon + 1, date->tm_mday,
date->tm_hour, date->tm_min, date->tm_sec);
return 0;
}
This program retrieves the current time, converts it to local time, and prints the year, month, day, hour, minute, and second.