liveBook · Manning

Time.h

As explained in Modern C, Third Edition

time.h is the C standard header that declares calendar-time types and functions, including struct tm and related interfaces.

The <time.h> header provides C interfaces for calendar time: timestamps represented by time_t, human-oriented dates represented by struct tm, conversion, comparison, and formatting. It also includes interfaces for physical time measured in seconds and nanoseconds. section 8.6 section 8.9

Designated initialization of a calendar time

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); Members such as tm_year and tm_mon use non-human-based offsets: tm_year counts from 1900 and tm_mon counts January as 0. tm_mday instead begins at 1. Unspecified members are initialized to zero. section 6.3.1

The principal calendar-time operations have distinct representations and responsibilities:

  • time(0) obtains the current timestamp as time_t; difftime computes the difference between two time_t values. section 8.6
  • struct tm stores seconds, minutes, hours, day, month, year, weekday, day-of-year, and daylight-saving status. section 8.6
  • mktime normalizes calendar members, computes weekday and day-of-year values, updates daylight-saving status when requested, and returns time_t. section 8.6
time_t time(time_t *t);
double difftime(time_t time1, time_t time0);
time_t mktime(struct tm tm[1]);
size_t strftime(char s[static 1], size_t max,
                char const format[static 1],
                struct tm const tm[static 1]);
int timespec_get(struct timespec ts[static 1], int base);
int timespec_getres(struct timespec ts[static 1], int base);

Browse the core declarations for timestamp acquisition, interval calculation, calendar conversion, formatting, and timespec resolution. section 8.6

How Modern C, Third Edition covers it

How deep it goes
Explains struct tm fields, normalization through mktime, and formatting directives with concrete declarations and examples.
Examples
Uses designated struct tm initialization, member access, year calculation, and strftime format-specifier tables.
What it assumes
Assumes basic C expressions while teaching struct members, designated initializers, and the nonuniform ranges used by struct tm.
What you can do after
Apply it via standard interfaces to obtain timestamps, represent calendar dates, normalize fields, compare times, and format output.
How it connects
Connects time_t, struct tm, difftime, mktime, strftime, calendar time, physical time, locales, and ISO 8601.

Also explained in

Compare how 2 books explain time.h →

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.