liveBook · Manning

Struct tm

As explained in Modern C, Third Edition

struct tm is the C standard-library structure type for representing broken-down calendar time components such as seconds, days, months, and years.

struct tm represents calendar time as named components: seconds, minutes, hours, day, month, year, weekday, day of year, and daylight-saving status. Named members avoid the ambiguity of storing date parts in array positions, and expressions such as today.tm_year access each component directly. section 6.3.1 section 8.6

struct tm {
  int tm_sec;  // Seconds after the minute    [0, 60]
  int tm_min;  // Minutes after the hour      [0, 59]
  int tm_hour; // Hours since midnight        [0, 23]
  int tm_mday; // Day of the month            [1, 31]
  int tm_mon;  // Months since January        [0, 11]
  int tm_year; // Years since 1900
  int tm_wday; // Days since Sunday           [0, 6]
  int tm_yday; // Days since January          [0, 365]
  int tm_isdst;// Daylight Saving Time flag
};

The member declarations make the representation and its principal ranges explicit. section 6.3.1

Designated initialization

struct tm today = { .tm_year = 2019 - 1900, .tm_mon = 4 - 1, .tm_mday = 3, .tm_hour = 10, .tm_min = 0, .tm_sec = 47, }; printf("this year is %d, next year will be %d\n", today.tm_year + 1900, today.tm_year + 1900 + 1); section 6.3.1

Interpret the fields carefully:

  • tm_mon starts at 0, so January is 0; tm_wday likewise starts at 0, with Sunday represented by 0. section 8.6
  • tm_mday starts at 1, tm_year stores the Gregorian year minus 1900, and tm_sec ranges from 0 through 60 for leap seconds. section 8.6
  • Omitted members in a struct initializer become zero, but zero does not necessarily make supplemental fields consistent with the date. section 6.3.1
  • mktime normalizes the hierarchical fields, computes tm_wday and tm_yday, updates an indeterminate tm_isdst flag, and returns a time_t representation. section 8.6

How Modern C, Third Edition covers it

How deep it goes
Defines members, encodings, initialization, consistency, and mktime normalization, but does not develop complete time-zone or formatting behavior.
Examples
Uses a 2019 date initializer, member-based year printing, and a day-of-year calculation that accounts for leap years.
What it assumes
Assumes C structures and member access while teaching field naming, designated initialization, zero initialization, and calendar-specific encodings.
What you can do after
Apply it via <time.h> to construct, inspect, normalize, convert, and format calendar-time values.
How it connects
Connects calendar fields with designated initializers, mktime, time_t, local time, UTC, and strftime.

Also explained in

Compare how 2 books explain struct tm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.