How to set timezone for localtime()

Giuseppe Modugno giuseppe.modugno.loqed@gmail.com
Fri Apr 6 07:48:00 GMT 2018


Il 05/04/2018 18:26, Brian Inglis ha scritto:
>
>> Now I have another similar question. I have to convert a struct tm in UTC to
>> time_t, but I set TZ to Italy timezone. Is there a function that makes this
>> convertion without checking current timezone configured in TZ?
> As mktime(3) assumes local time, and there are no currently supported context or
> locale variants (GNU timegm(3), BSD/tzcode mktime_z(3)), after the previous
> code, you should use:
>
> 	putenv("TZ=UTC0");
> 	tzset();
> 	struct tm stm_utc;
> 	stm_utc.tm_year		= year - 1900;
> 	stm_utc.tm_month	= month - 1;
> 	stm_utc.tm_mday		= day;
> 	stm_utc.tm_hour		= hour;
> 	stm_utc.tm_min		= min;
> 	stm_utc.tm_sec		= sec;
> 	stm_utc.tm_isdst	= 0;
> 	time_t tt_utc = mktime(&stm_utc);
>

As you can read in my previous posts, putenv() calls setenv() that 
allocates a new string every time (if the new value is longer than the 
old value).
My application needs to call mktime() with "TZ=UTC0" and localtime() 
with "TZ=CET..." regularly and I can't call continuously 
setenv()/unsetenv(), because of a memory leak (unsetenv() doesn't call 
free).

Another unpleasent thing happens with tzset() (that I *need* to call 
every time I change "TZ" variable). tzset() allocates and save the 
previous value of "TZ" variable. Every time it checks if the value is 
different. If yes, it free() and malloc() the new value (and make all 
the timezone calculations).
In this case there isn't any memory leak, however I'm indirectly and 
continuously calling malloc()/free().




More information about the Newlib mailing list