Tutorial :Converting between timezones in C


I need to convert time between timezones in C (on linux, so anything specific would do too).

I know my current time, local and UTC, I have the offset of the target time. I am trying to use mktime, gmtime, localtime and similar set of functions but still can't figure it out.

Thanks in advance.


As comments do not allow posting the code, posting as a separate answer.. If you know "local" time and "UTC" time, you can calculate the offset of the "other" time from your "local" time. Then you convert the struct tm into calendar time, add the desired number of seconds (being the offset of the target time), and convert it back to struct tm:

(edited to account for another scenario to use mktime's normalization)

#include <stdio.h>  #include <stdlib.h>  #include <time.h>  #include <sys/time.h>    int main(int argc, char *argv) {    struct timeval tv_utc;    struct tm *local_tm, *other_tm;      /* 'synthetic' time_t to convert to struct tm for the other time */    time_t other_t_synt;    /* Other time is 1 hour ahead of local time */    int other_local_delta = 1*3600;         /* the below two lines are just to set local_tm to something */    gettimeofday(&tv_utc, NULL);    local_tm = localtime(&tv_utc.tv_sec);      printf("Local time: %s", asctime(local_tm));      #ifdef DO_NOT_WRITE_TO_LOCAL_TM    other_t_synt = mktime(local_tm) + other_local_delta;    #else    local_tm->tm_sec += other_local_delta;    /* mktime will normalize the seconds to a correct calendar date */    other_t_synt = mktime(local_tm);    

Next Post »