Get the latest tech news

The surprising struggle to get a Unix Epoch time from a UTC string in C or C++


So how hard could it be. As input we have something like Fri, 17 Jan 2025 06:07:07 in UTC, and we’d like to turn this into 1737094027, the notional (but not actual) number of seconds that have passed since 1970-01-01 00:00:00 UTC. Trying to figure this out led me to discover many ‘surprise features’ and otherwise unexpected behaviour of POSIX time handling functions as implemented in various C libraries & the languages that build on them.

Pass the struct tm calculated by strptime() to the pre-standard function timegm()( mkgmtime() on Windows) to get the correct UNIX epoch timestamp for your UTC time string. One major role of struct tm is as input to mktime(), which as part of its work turns a ‘broken-down time according to your local TZ ’ into a UNIX epoch timestamp. Being truly luxurious, the tz library supports using not just your operating system’s time zone databases, which might lack crucial leap second detail, but can also source the IANA tzdb directly.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of utc

utc

Photo of C++

C++

Photo of Unix epoch

Unix epoch

Related news:

News photo

Expressive Vector Engine – SIMD in C++

News photo

Fish Shell Outlines Their Successes & Challenges Going From C++ To Rust

News photo

C++ is an absolute blast