C time localtime() Function
Example
Print the current year, month and day:
time_t now = time(NULL);
struct tm *t = localtime(&now);
printf("Year: %d\n", t->tm_year + 1900);
printf("Month: %d\n", t->tm_mon + 1);
printf("Day: %d\n", t->tm_mday);
Definition and Usage
The localtime() function converts a time_t value into a struct tm in local time (the time zone of the computer that runs the program).
A struct tm holds the parts of a date and time in separate members, like tm_year and tm_mday. See all members on the C time Library page.
Note: tm_year counts the years since 1900, and tm_mon starts at 0 for January. That is why the example adds 1900 and 1.
The localtime() function is defined in the <time.h> header file.
Syntax
struct tm *localtime(const time_t *timer);
Parameter Values
| Parameter | Description |
|---|---|
| timer | Required. A pointer to a time_t value, for example from time(). |
Technical Details
| Returns: | A pointer to a struct tm with the local date and time, or NULL if the time cannot be converted. The struct is shared, so the next call to localtime() or gmtime() overwrites it. |
|---|
Related Pages
Read more about dates and times in our C Date and Time Tutorial.