Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use mktime to respect timezone

Tags:

c++

linux

gnu

How do I create timezone aware struct tm in Linux/gcc ? I have the following code:

struct tm date;
date.tm_year=2012-1900;
date.tm_mon=9;
date.tm_mday=30;
date.tm_hour=17;
date.tm_min=45;
date.tm_sec=0;
date.tm_zone="America/New_York";
time_t t = mktime(&date);

When I print t the value is 1349045100. So I take this uses both c++ and python to print as string, it returns me: Sun Sep 30 18:45:00 2012 which is one hour off. I want 17:45 not 18:45. The python command I am using is:

 time.ctime(1349045100)

C++ I am using is:

::setenv("TZ", "America/New_York",1);
::tzset();
strftime(tm_str, len_tm_str, "%Y%m%d %H:%M:%S", ::localtime(&t));

So it seems when I construct the time it is already one hour off. How do I correct this?

like image 665
user2426361 Avatar asked Jan 28 '26 03:01

user2426361


1 Answers

You problem is almost certainly that the tm_isdst flag of your tm struct defaulted to 0 which caused it to assume no DST even in summer (which your date is). Then when you converted back to localtime it DID add the DST offset, causing the difference you note.

The simplest and often correct solution is to set the tm_isdst member to -1 to let mktime figure out if the date in question should have a DST offset applied.

Note that whether DST is in effect is orthogonal to which timezone you're using. Both need to be set in the correct way for the results to come out correctly.

Also do consider using localtime_r instead of localtime if there's any chance of your application being threaded.

like image 132
Mark B Avatar answered Jan 29 '26 20:01

Mark B