Converting time from timezone string to another timezone time

Jeffrey Walton noloader@gmail.com
Tue Feb 2 14:33:13 GMT 2021


On Fri, Jan 29, 2021 at 3:11 AM Jeffrey Walton <noloader@gmail.com> wrote:
>
> Hi Everyone,
>
> I'm having a heck of a time converting a time from a timezone string
> to another timezone time. The best I seem to be able to do is adjust
> for DST using strptime, mktime and localtime. For example:
>
>   * given: '15 Jan 2021 01:24:55 -0800 (PST)'
>   * expected: '15 Jan 2021 04:24:55 -0500 (EST)' (or similar, as long
> as it includes 04:24:55)
>   * my best result: '15 Jan 00:24:55 2021' (seems to be a DST adj of PST time)
>
> I've been through the manual at
> https://www.gnu.org/software/libc/manual/html_node/Calendar-Time.html
> but I can't seem to find the sequence of calls to perform the actions.
> I've also been through the libc FAQ at
> https://sourceware.org/glibc/wiki/FAQ (there's one topic on
> timezones).
>
> So I have two questions, but I only need one answered (whichever is
> easier to answer):
>
> 1. Where is the discussion/faq on how to convert from timezone string
> to another timezone time?
>
> 2. What is wrong with this code (error checking omitted)?
>
>     const char pst_timestring[] = '15 Jan 2021 01:24:55 -0800 (PST)';
>     struct tm gmail_tm[1];
>     strptime(pst_timestring, "%d %b %Y %T %z", gmail_tm);
>
>     // Already set, but just in case. It is -0500 (EST)
>     char my_timezone[] = "TZ=America/New_York";
>     putenv(my_timezone);
>
>     time_t utc_time;
>     utc_time = mktime(gmail_tm);
>
>     struct tm local_tm[1];
>     local_tm = localtime(&utc_time);
>
>     // This prints a time that was adjusted by 1 hour, not 3 hours
> (expected from -0800 to -0500)
>     printf(..., asctime(local_tm));
>     // Output is similar to '15 Jan 00:24:55 2021'
>
> Somewhere there is a non-obvious problem with the code stitched
> together from the man pages.

Ping...

Does anyone know why libc can't seem to do this simple task?


More information about the Libc-help mailing list