Course contentsShow
← C
Lesson 892 of 1,21912. The Standard LibraryFree lesson

Converting `time_t` to local time with `localtime`

Converting time_t to local time with localtime

What you'll learn: How to translate a raw Unix timestamp into a human-readable structure that respects your local time zone.

The Raw Stamp vs. The Calendar

In C, the time_t type represents time as a single, massive integer—usually the number of seconds elapsed since January 1, 1970. While this is great for computers to calculate durations, it is impossible for a human to look at 1709289600 and know it’s a Friday afternoon in March.

Think of time_t like a giant jar of pennies. If you want to know how many dollars, quarters, and nickels you have, you need to sort them into slots. The localtime() function is your "sorter." It takes that raw number and breaks it down into a struct tm, which contains separate variables for years, months, days, hours, and minutes.

Using the localtime Function

The localtime() function lives in <time.h>. It takes a pointer to your time_t variable and returns a pointer to a struct tm. Crucially, this function automatically adjusts the time based on your computer’s local time zone settings.

#include <stdio.h>
#include <time.h>

int main() {
    time_t raw_time;
    struct tm *info;

    // 1. Get the current raw time
    time(&raw_time);

    // 2. Convert to local time structure
    info = localtime(&raw_time);

    // 3. Access specific components
    // Note: tm_year is years since 1900, tm_mon is 0-11
    printf("Current year: %d\n", info->tm_year + 1900);
    printf("Current month: %d\n", info->tm_mon + 1);
    printf("Current hour: %d\n", info->tm_hour);

    return 0;
}

Important Quirks

When you look inside the struct tm returned by localtime, there are two "gotchas" that trip up every C programmer:

  1. The Year Offset: The tm_year member starts counting from 1900. To get the actual year, you must add 1900.
  2. Zero-based Months: The tm_mon member ranges from 0 (January) to 11 (December). You usually need to add 1 to show it to a user.

Lastly, be aware that localtime returns a pointer to a "static" area of memory. This means if you call the function again, the data in that memory will be overwritten. If you need to keep a specific time around, copy the contents of the struct into your own variable.

Key takeaway

Use localtime() to break down a raw time_t value into a struct tm for easy access to years, months, and hours adjusted to the local time zone.