C++ ctime mktime() Function
Example
Create a timestamp and print its date and time:
struct tm date;
time_t timestamp;
date.tm_year = 2023 - 1900; // Number of years since 1900
date.tm_mon = 12 - 1; // Number of months since January
date.tm_mday = 17;
date.tm_hour = 12;
date.tm_min = 30;
date.tm_sec = 1;
date.tm_isdst = -1;
timestamp = mktime(&date);
cout << ctime(×tamp);
Try it Yourself »
Definition and Usage
The mktime() function creates a timestamp for a date and time from a tm structure. The time represented by the structure is treated as being in the computer's local time zone.
The mktime() function also changes the tm structure by correcting overflowing dates and filling in the tm_wday and tm_yday members.
The mktime() function is defined in the <ctime> header file.
The timestamp usually represents a number of seconds relative to the unix epoch (January 1, 1970) but it depends on how the library is implemented, so it is safer to only use it with functions designed to handle timestamps such as localtime() and difftime().
The mktime() function uses the following members of the tm structure to create the timestamp:
- tm_sec - The seconds within the minute
- tm_min - The minutes within an hour
- tm_hour - The hour within a day (from 0 to 23)
- tm_mday - The day of the month
- tm_mon - The month (from 0 to 11 starting with January)
- tm_year - The number of years since 1900
- tm_isdst - 1 when daylight saving time is in effect, 0 when not in effect and -1 to use the computer's timezone setting
The mktime() also accounts for overflows and underflows in dates. For example, the code below interprets April 31 correctly as May 1.
More Examples
Example
The mktime() function can interpret overflowing dates:
struct tm date;
time_t timestamp;
date.tm_year = 2024 - 1900; // Number of years since 1900
date.tm_mon = 4 - 1; // Number of months since January
date.tm_mday = 31;
date.tm_hour = 0;
date.tm_min = 0;
date.tm_sec = 0;
date.tm_isdst = -1;
timestamp = mktime(&date);
cout << ctime(×tamp);
Try it Yourself »
Syntax
mktime(struct tm * time);
Parameter Values
| Parameter | Description |
|---|---|
| time | Required. A pointer to a tm structure. |
Technical Details
| Returns: | A time_t timestamp representing the date and time given in the structure. |
|---|