The commonly available timegm() function interprets a struct tm as UTC and converts it to time_t. Unlike mktime(), it does not interpret the fields as local time.
It is standardized by POSIX.1-2024 and is also a long-standing extension on many systems, but older C/POSIX environments may not declare it. The function normalizes fields and modifies the supplied structure. Include <time.h>.
Syntax
Start with this concrete timegm() call:
C
timegm(&utc);
Call
What it does
timegm(&utc);
Interprets and normalizes utc as UTC, then returns calendar time.
Declare the required objects with the time types shown below, include <time.h>, and check the documented result before using output data.
Library declaration
C
time_t timegm(struct tm *time_ptr);
Parameters
Parameter
Description
time_ptr
Pointer to a writable struct tm interpreted as UTC.
Return Value
Return Value
Description
time_t value
Calendar-time representation of the normalized UTC fields.
(time_t)-1
The UTC value cannot be represented.
C Examples
Example 1 — Build a UTC Instant
This example demonstrates timegm() with a small, complete program and checks the relevant result before using it.
Step 1. Use month 12, one past the normal zero-based range.
Step 2. Treat all fields as UTC rather than local time.
Step 3. Conversion carries the extra month into the next year.
Step 4. Read the normalized fields written back by timegm().
Example 3 — Round Trip Through UTC
This example demonstrates timegm() with a small, complete program and checks the relevant result before using it.
C
#include <stdio.h>
#include <time.h>
int main(void) {
time_t original = (time_t)0;
struct tm *ptr = gmtime(&original);
if (ptr != NULL) {
struct tm utc = *ptr;
time_t again = timegm(&utc);
printf("round trip: %s\n", again == original ? "yes" : "no");
}
return 0;
}
Output
round trip: yes
How It Works
Step 1. Break a calendar value into UTC fields.
Step 2. Copy the static gmtime() result into writable storage.
Step 3.timegm() converts those UTC fields back.
Step 4. The comparison confirms the two operations describe the same representable instant.
Frequently Asked Questions
timegm() converts UTC broken-down time to calendar time.
Include <time.h> before calling timegm().
On success it returns the time_t for the UTC fields. On failure it returns (time_t)-1. timegm() is a common extension, not ISO C.
Check availability and feature-test requirements on the target platform. Do not emulate timegm() by temporarily changing the process time zone in multi-threaded code.
It is standardized by recent POSIX and common as an extension, but older platforms may not provide it.