[tz] strftime %s

Paul Eggert eggert at cs.ucla.edu
Tue Jan 16 01:34:25 UTC 2024


On 2024-01-14 14:46, Robert Elz wrote:

>    | > 	The struct tm handed to strftime must be one returned by
>    | > 	an immediately preceding call to localtime or gmtime.
>    |
>    | This is good advice,
> 
> It actually isn't.   It isn't required at all.

Although it's not required, it's good advice anyway. Calling strftime 
can be a tricky business (as this thread demonstrates) and following the 
advice means one needn't worry about many of the tricks.

What I've found, when I want to format a timestamp that localtime etc. 
didn't generate, is that I'm typically better off not using strftime. E.g.:

   printf ("Etc/GMT%+d", - (gmtoff / (60 * 60)));

This is better than stuffing gmtoff into a struct tm's tm_gmtoff and 
then using strftime followed by printf - notably because strftime can't 
even generate this particular format.

Most applications are in a similar boat, and stick with timestamps 
generated by localtime etc. when calling strftime. It's exceptional to 
see otherwise, for good reason.


> A C time_t
> might be a count of milliseconds, of microseconds, or 2-seconds, or
> BCD encoded, or almost anything (though I think it is now required
> to be an integer type - I believe it was once allowed to be a float).

Actually in C a time_t can be floating point. It can even be an 
enumerated type, or bool.

POSIX formerly allowed time_t to be floating-point, but that was changed 
in POSIX-2008 as a result of DR 327 
<https://www.austingroupbugs.net/view.php?id=327>. In POSIX-2017, time_t 
can still be bool (!) but in POSIX 202x/D4 the constraints on time_t 
have changed again: now it must be an integer type that is at least 64 
bits wide. (Why 64 bits? Surely 60 bits would have been enough for 
real-world timestamps....)



More information about the tz mailing list