Namespaces
Variants

std::timegm

From cppreference.com
< cpp | chrono | c
 
 
 
C-style date and time utilities
Functions
Time manipulation
Format conversions
(deprecated in C++26)
(deprecated in C++26)
(C++26)
Constants
Types
(C++17)
 
Defined in header <ctime>
time_t timegm( struct tm* timeptr );
(since C++26)

Converts the broken-down UTC time in timeptr into a calendar time with the same encoding as the values returned by the std::time(). The original values of the tm_wday and tm_yday of the timeptr are ignored, and the original values of the other components are not restricted to the ranges indicated previously.

On success, the tm_wday and tm_yday are set appropriately, and the other components are set to represent the specified calendar time, but with their values set to the ranges indicated previously. The final value of tm_mday is not set until tm_mon and tm_year are determined.

Parameters

timeptr - a pointer to an object of type std::tm

Return value

The specified calendar time encoded as a value of type time_t.

Returns (std::time_t)(-1) and does not change the value of the tm_wday, if the calendar time cannot be represented in the std::time_t encoding or the value in the tm_year cannot be represented as an int.

Example

#include <cstdio>
#include <cstdlib>
#include <ctime>

int main()
{
    std::tm tm_utc;
    tm_utc.tm_year  = 2024 - 1900; // years since 1900
    tm_utc.tm_mon   = 2 - 1;       // months since January (0‑11)
    tm_utc.tm_mday  = 15;          // day of the month
    tm_utc.tm_hour  = 12;
    tm_utc.tm_min   = 30;
    tm_utc.tm_sec   = 45;
    tm_utc.tm_isdst = 0;            // DST flag not used for UTC

    // Convert the broken‑down UTC time to a time_t value.
    // timegm() assumes the struct tm describes UTC, avoiding any
    // timezone or DST adjustments that localtime() would apply.
    std::time_t utc_seconds = timegm(&tm_utc);
    if (utc_seconds == static_cast<time_t>(-1))
    {
        std::perror("timegm");
        return EXIT_FAILURE;
    }

    std::printf("UTC time: %04d-%02d-%02d %02d:%02d:%02d → %ld seconds since the epoch\n",
           tm_utc.tm_year + 1900,
           tm_utc.tm_mon  + 1,
           tm_utc.tm_mday,
           tm_utc.tm_hour,
           tm_utc.tm_min,
           tm_utc.tm_sec,
           static_cast<long>(utc_seconds));

    std::tm check;
    gmtime_r(&utc_seconds, &check);
    std::printf("Back‑converted: %04d-%02d-%02d %02d:%02d:%02d UTC\n",
           check.tm_year + 1900,
           check.tm_mon  + 1,
           check.tm_mday,
           check.tm_hour,
           check.tm_min,
           check.tm_sec);
    return EXIT_SUCCESS;
}

Possible output:

UTC time: 2024-02-15 12:30:45 → 1708000245 seconds since the epoch
Back‑converted: 2024-02-15 12:30:45 UTC

See also

converts time since epoch to calendar time expressed as Universal Coordinated Time
(function) [edit]
returns the current time of the system as time since epoch
(function) [edit]
C documentation for timegm