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

Breaking down time with `struct tm`

Breaking down time with struct tm

What you'll learn: How to use the tm structure to translate raw seconds into human-readable components like hours, days, and years.

From Seconds to Calendars

In C, the computer usually tracks time as a single, massive number: the total seconds elapsed since January 1, 1970. While this is great for math, it is useless for humans. If you want to print "It is currently 3:30 PM," you don't want to manually calculate how many leap years have passed since 1970.

This is where struct tm comes in. Think of it as a sorting tray. You hand the C library that big pile of seconds, and it sorts them into labeled slots: one for minutes, one for hours, one for the day of the month, and so on.

The Anatomy of struct tm

Defined in <time.h>, the tm struct breaks time into several integer fields. Here are the most common ones you will use:

  • tm_sec: Seconds (0–60)
  • tm_min: Minutes (0–59)
  • tm_hour: Hours (0–23)
  • tm_mday: Day of the month (1–31)
  • tm_mon: Month (0–11) — Note: January is 0!
  • tm_year: Years since 1900 — Note: You must add 1900 to get the current year.

Seeing it in Action

To fill this struct, we use the localtime() function. It takes the raw timer and "explodes" it into the tm format based on your computer's local settings.

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

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

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

    // 2. Convert seconds into the broken-down 'tm' struct
    info = localtime(&raw_time);

    // 3. Access individual pieces
    printf("Current year: %d\n", info->tm_year + 1900);
    printf("Current month: %d\n", info->tm_mon + 1);
    printf("Current time: %02d:%02d:%02d\n", 
            info->tm_hour, info->tm_min, info->tm_sec);

    return 0;
}

Two Common Traps

When using struct tm, remember two historical quirks. First, the month is zero-indexed, so December is 11. Second, the year starts at 1900. If the struct says the year is 124, it means 1900 + 124, which is 2024. Always remember to add those offsets when displaying dates to your users!

Key takeaway

The tm struct translates a single raw timestamp into a readable format by separating time into logical components like hours, days, and years.