mktime() function in C++

In this guide, you will learn what is mktime() function is in C++ programming and how to use it with an example.

1. mktime() Function Overview

The mktime() function in C++ is used to convert a local time (given as a tm structure) into a time_t calendar time representation. It also normalizes the tm structure if any fields are outside their valid range. This function is defined in the <ctime> header file.

Signature:

time_t mktime(struct tm* timeinfo);

Parameters:

- timeinfo: Pointer to a tm structure that contains the local time to be converted.

2. Source Code Example

#include <iostream>
#include <ctime>

int main() {
    struct tm y2k = {};
    double seconds;

    y2k.tm_hour = 0;
    y2k.tm_min = 0;
    y2k.tm_sec = 0;
    y2k.tm_year = 100;  // Year since 1900 (so, 2000)
    y2k.tm_mon = 0;     // January
    y2k.tm_mday = 1;    // First day

    // Convert tm structure to time_t value
    time_t y2k_time = mktime(&y2k);

    // Get current time
    time_t current_time;
    time(&current_time);

    // Calculate difference in seconds
    seconds = difftime(current_time, y2k_time);

    std::cout << "Time since January 1, 2000 in seconds: " << seconds << std::endl;

    return 0;
}

Output:

Time since January 1, 2000 in seconds: X

Note: The value of X will vary based on the current date and time.

3. Explanation

1. A tm structure named y2k is initialized to represent the time of January 1, 2000, 00:00:00.

2. The mktime() function is used to convert this structure to a time_t value.

3. The current calendar time is obtained using the time() function.

4. The difftime() function calculates the difference in seconds between the current time and the Y2K time.

5. The result, which represents the time since January 1, 2000, in seconds, is printed to the console.


Comments