mktime() Function Example in C Programming

In this source code example, we will see how to use the mktime() function in C programming with an example.

mktime() Function Overview

The mktime() function in C transforms a struct tm representation of local time into a calendar time value (time_t). It's a helpful tool when working with manual date and time adjustments or conversions. This function resides within the time.h library. 

Key Points: 

- You'll need the time.h header to use mktime()

- The function is used to normalize or adjust user-specified date and time values. 

- It can be handy for tasks like calculating the day of the week for a given date. 

- A NULL return value indicates an error.

Source Code Example

#include <stdio.h>
#include <time.h>  // Required for mktime(), localtime() and time()

int main() {
    struct tm timeinfo;
    time_t time_of_day;

    // Set up a specific date: July 20, 2023, 14:30:00
    timeinfo.tm_year = 2023 - 1900;  // Year since 1900
    timeinfo.tm_mon = 6;             // July
    timeinfo.tm_mday = 20;
    timeinfo.tm_hour = 14;
    timeinfo.tm_min = 30;
    timeinfo.tm_sec = 0;
    timeinfo.tm_isdst = -1;          // Allow the library to determine DST

    time_of_day = mktime(&timeinfo);

    if (time_of_day == (time_t)-1) {
        printf("Error in converting tm to time_t.\n");
        return 1;
    }

    // Display the week day. After mktime, timeinfo is normalized.
    printf("The date specified is a %s.\n", asctime(&timeinfo));

    return 0;
}

Output

The date specified is a Thu Jul 20 14:30:00 2023
(Note: The output might vary based on local settings and daylight saving adjustments.)

Explanation

1. Required header files are included: stdio.h for input/output functions and time.h for mktime(), asctime(), and related time functions.

2. Inside the main() function, a struct tm named timeinfo is set up to represent July 20, 2023, at 14:30:00.

3. mktime() is then called to normalize the provided time structure and return the corresponding time_t value.

4. Error checking is performed by seeing if the returned time_t value is (time_t)-1.

5. The day of the week is displayed using asctime(), which shows that mktime() has normalized the struct tm and populated any missing information (like the day of the week).

The mktime() function is especially useful when performing operations like date arithmetic or when validating and normalizing user-inputted date and time values.


Comments