Creating time_t value from a UTC date and time in C

Programming with time is difficult and error prone, for this reason I usually try to keep things in UTC so that I don’t have to worry about time zones and daylight saving offsets etc.

When in C++ I mostly use the boost::ptime library but I was surprised recently about tricky it seemed to be to initialise a time_t value for an arbitrary UTC time just using the standard C/C++ libs. We can’t use mktime() as it will figure out which time zone you’re in and assume that the time values you have passed refer to this zone, it will also apply daylight saving offsets.

Anyway to cut a long story short there are no standard functions in the C lib for this, instead your either have to use the posix timegm() function on Unix-like systems and _mkgmtime() on windows systems.

Here is an example, lets say we want to initialise a time_t value for this UTC date/time: 01/10/2020 10:16:03 (10th. Jan 2020)

That seems to do the trick, although I am astounded that this isn’t covered by the standard lib. To achieve the same using just the standard lib it seems you have to either hack around with the timezone env. variable before calling mktime() or assume you know how the time_t val is constructed and build your own timegm() function…