Converting time_t to UTC with gmtime
What you'll learn: How to translate a raw Unix timestamp into a readable structure representing Universal Coordinated Time (UTC).
The Raw vs. The Readable
In C, the time_t type is like a giant stopwatch counting every second since January 1, 1970. While it is great for math, it is terrible for humans. If you tell someone the time is "1709289600," they won’t know you mean midnight on March 1st.
To make sense of this number, we use the gmtime function. Think of gmtime as a translator that takes a single massive number and breaks it down into a "broken-down time" structure called struct tm.
The struct tm Map
When you pass a timestamp to gmtime, it fills out a struct containing separate fields for the year, month, day, hour, minute, and second. Specifically, gmtime converts the time to UTC (Greenwich Mean Time), which is the global scientific standard, ignoring local time zones or daylight savings.
Here is how you use it in practice:
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL); // Get current raw time
// gmtime takes a pointer to time_t and returns a pointer to a struct tm
struct tm *utc_time = gmtime(&now);
// Accessing members of the struct
printf("UTC Date: %04d-%02d-%02d\n",
utc_time->tm_year + 1900, // Years since 1900
utc_time->tm_mon + 1, // Months 0-11
utc_time->tm_mday); // Day of the month
printf("UTC Time: %02d:%02d:%02d\n",
utc_time->tm_hour,
utc_time->tm_min,
utc_time->tm_sec);
return 0;
}
Important Quirks
There are two "gotchas" when using the results of gmtime:
- Offset values: The
tm_yearfield counts years since 1900 (so 2024 is stored as 124), andtm_monis zero-indexed (January is 0, not 1). You must add 1900 and 1 respectively to get the values we use in daily life. - Shared Memory: The
gmtimefunction returns a pointer to a static internal buffer. If you callgmtimeagain, the data in that pointer will be overwritten with the new time. If you need to keep the old time, copy the struct to your own variable.
Key takeaway
Use gmtime to break a raw time_t into a readable struct tm format based on the universal UTC standard.