mktime() gives different UTC results for the same local time across C libraries — which behavior is correct?
0 reputation · 09 May 2021, 01:41 UTC
Goal
I need portable date conversion in C using only <time.h>: given a broken-down local time in a struct tm, convert it to time_t with mktime() and later recover the same wall-clock time with localtime(). The target zone is selected through the TZ environment variable plus tzset() on POSIX systems.
Constraint
My understanding is that when a local time is ambiguous (repeated at the fall-back DST transition) or nonexistent (skipped at spring-forward), the mapping performed by mktime() is implementation-defined. With tm_isdst = -1 the library decides, and different C libraries may pick either side of the transition or normalize the fields differently. Forcing tm_isdst to 0 or 1 can shift the result by an hour near transitions.
Questions
- Is there any portable way, within standard C or POSIX
<time.h>, to detect that a givenstruct tmfell into an ambiguous or nonexistent local time, rather than silently accepting whichever instantmktime()chose? - Does round-tripping through
localtime(mktime(&tm))reliably reveal such cases on glibc, musl, and the BSDs, or is that also implementation-defined? - If detection is not portable, is the accepted approach to delegate zone handling to the OS's IANA tz database via
TZand document the ambiguity behavior per platform?