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

Converting `struct tm` back to `time_t` with `mktime`

Converting struct tm back to time_t with mktime

What you'll learn: How to use the mktime function to translate a human-readable calendar structure back into a single Unix timestamp.

The Two-Way Street of Time

Imagine you have a recipe. A struct tm is like the ingredients list: it shows you the year, month, and day as separate items. A time_t value is like the finished cake: one single object that represents the whole thing.

Earlier, you learned how to break a timestamp down into a structure. But what if you want to do the opposite? Perhaps you are writing a scheduling app where a user types in their birthday, and you need to calculate how many seconds have passed since then. This is where mktime comes in. It takes your "ingredients" (struct tm) and bakes them back into a single number of seconds since the Unix Epoch.

How mktime Works

The mktime function is smart. When you pass it a pointer to a struct tm, it looks at the date you provided and returns a time_t value.

One "magic" feature of mktime is that it fixes your math. If you set the date to "March 32nd," mktime will automatically adjust it to "April 1st" and update the structure for you. It also fills in the tm_wday (day of the week) automatically, which is a great way to find out what day a specific date falls on.

A Practical Example

Here is how you would convert a specific date (July 4, 2024) into a Unix timestamp:

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

int main() {
    struct tm my_date = {0}; // Initialize to zero

    // Setting up: July 4, 2024
    my_date.tm_year = 2024 - 1900; // Years since 1900
    my_date.tm_mon = 6;            // July is 6 (0-indexed)
    my_date.tm_mday = 4;           // The day of the month

    // Convert to time_t
    time_t timestamp = mktime(&my_date);

    if (timestamp == -1) {
        printf("Error: Could not convert time.\n");
    } else {
        printf("The timestamp is: %ld\n", (long)timestamp);
        printf("That day was a: %d (0=Sunday, 4=Thursday)\n", my_date.tm_wday);
    }

    return 0;
}

In this code, we manually fill the structure. Notice that mktime modifies the original my_date variable to fill in the day of the week, saving you from doing the complex calendar math yourself.

Key takeaway

Use mktime to turn human-readable date components into a single time_t value for easy comparison or storage.