Convert between time zones to C

I need to convert the time between time zones in C (on linux, so there will be nothing concrete either).

I know my current time, local and UTC, I have a target time offset. I am trying to use mktime, gmtime, localtime and a similar set of functions, but still can not understand.

Thanks in advance.

+6
c timezone
source share
3 answers

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

(edited to accommodate another scenario to use mktime 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); #endif other_tm = localtime(&other_t_synt); printf("Other time: %s", asctime(other_tm)); exit(0); } 
+5
source share

You can use gmtime () and the tm structure to directly set this if you know the offsets.

If you know your local time and UTC, you know your local offset. If you also know the target offset, it is just a matter of setting tm_hour to the appropriate one (and possibly scrolling through the day if you go <0 or> 23).

For some sample code, see this gmtime man page . It shows the offset based on the offsets of the time intervals.


Edit:

In response to comments - you can also let mktime handle the shift for you, which allows you to simplify this conversion back to time_t. You can use something like:

 time_t currentTime; tm * ptm; time ( &currentTime ); ptm = gmtime ( &rawtime ); ptm->tm_hour += hours_to_shift; ptm->tm_minutes += minutes_to_shift; // Handle .5 hr timezones this way time_t shiftedTime = mktime( ptm ); // If you want to go back to a tm structure: tm * pShiftedTm = gmtime( &shiftedTime ); 
+2
source share

It is likely that your operating system provides some support for this.

On Unix operating systems, you can see the manual pages for asctime, asctime_r, ctime, ctime_r, difftime, gmtime, gmtime_r, localtime, localtime_r, mktime, timegm .

0
source share

All Articles