The surprising struggle to get a UNIX Epoch time from a UTC string in C or C++ - Bert Hubert's writings
2 days ago
- Converting UTC time strings to UNIX epoch timestamps in C/C++ is surprisingly difficult due to quirks in POSIX time functions like `mktime()` and `strptime()`.
- `mktime()` ignores `tm_gmtoff` and `tm_zone`, always interprets input as local time, and normalizes `struct tm` with side effects; reusing `tm_isdst` requires resetting to -1.
- `strptime()` with `%z` or `%Z` is unreliable for timezone parsing, and its behavior depends on locale; calling `setlocale()` can break English-only time string parsing.
- The recommended approach for UTC parsing is to use `timegm()` (or `mkgmtime()` on Windows) instead of manipulating TZ environment variable or relying on `mktime()`.
- C++ offers better solutions: `std::get_time` with per-stream locale for locale-independent parsing, and the C++20 timezone library (Howard Hinnant's tz) for robust timezone conversions.