← The C Language Lesson 61 of 77 · 10 XP

Date and time

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Time in C lives in the <time.h> header:

time_t now = time(NULL);              // seconds since 1 January 1970 (Unix time)
struct tm *t = localtime(&now);       // split into year, month, day…
printf("%d-%02d-%02d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);

The fields of struct tm have catches:

  • tm_year — years since 1900 (2026 → 126);
  • tm_mon — the month from zero (January = 0);
  • tm_mday — the day from one;
  • tm_wday — the day of the week, 0 = Sunday.

To go back from the fields to a time, use mktime(&tm). Along the way it normalises the date: 32 January turns into 1 February, and it fills in tm_wday. A simple way to find the day of the week of any date is based on this.

Formatting: strftime(buf, size, "%d.%m.%Y %H:%M", t).

The difference between two moments in seconds: difftime(t2, t1).

To measure how long a piece of code takes: clock() returns the processor time, and (double)clock() / CLOCKS_PER_SEC is the same time in seconds.

Task. Read a date day month year and print the day of the week in English (Monday, Tuesday…). Use mktime and tm_wday. So that daylight saving time doesn't shift the date, set the time to noon: tm_hour = 12.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.