CodeBlanks Logo Icon CodeBlanks

time.h

  • C course
  • Intermediate
  • Lesson 85/116
  • 5 min

Learn date and time with time.h.

time.h

The <time.h> header provides date and time operations: time_t (time type), struct tm (broken-down time) and mktime (converts broken-down time to a timestamp).

struct tm splits a date into parts: tm_year (years since 1900), tm_mon (month 0–11), tm_mday (day of month), tm_wday (day of week 0–6; 0 is Sunday). mktime(&t) computes and fills missing fields (such as tm_wday). Example: struct tm t = {0}; t.tm_year = 100; t.tm_mon = 0; t.tm_mday = 1; mktime(&t);. After this t.tm_wday gives the weekday of January 1, 2000. time(NULL) returns the current timestamp; but this value changes each run, so it's not deterministic.

Finding weekday with mktime

mktime not only gives a timestamp; it also fills in missing fields in struct tm. This lets us find the weekday of a given date.

For January 1, 2000: struct tm t = {0}; t.tm_year = 100; t.tm_mon = 0; t.tm_mday = 1; mktime(&t);. After the call t.tm_wday is 6; because January 1, 2000 was a Saturday (0=Sunday, 6=Saturday). Initializing with struct tm t = {0} is important; otherwise unused fields may hold garbage and mktime may give wrong results. This technique is common for finding the weekday of a specific date; used in calendar or scheduling apps.

Practice Find the weekday

In main start with struct tm t = {0};. Set t.tm_year = 100;, t.tm_mon = 0;, t.tm_mday = 1;. Call mktime(&t);. Print with printf("Day: %d\n", t.tm_wday);.

Starter code

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

// main: declare struct tm and zero it
// tm_year = 100 (year 2000), tm_mon = 0 (January), tm_mday = 1
// normalize with mktime, print tm_wday

int main(void) {
    // write here
    return 0;
}

Sample solution

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

int main(void) {
    struct tm t = {0};
    t.tm_year = 100;
    t.tm_mon = 0;
    t.tm_mday = 1;
    mktime(&t);
    printf("Day: %d\n", t.tm_wday);
    return 0;
}

Expected output

Day: 6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In struct tm, what month does tm_mon = 0 denote?

  • February
  • January Correct answer
  • New Year
  • December

Explanation: tm_mon ranges 0–11; 0 is January.

2 Year setting

Question
t.tm_____ = 100;  // year 2000
Answer
t.tm_year = 100;  // year 2000

Explanation: tm_year counts from 1900; 100 → 2000.

3 struct tm fields

Term Meaning
tm_year year (since 1900)
tm_mon month (0–11)
tm_mday day of month
tm_wday day of week

All lessons in Intermediate