cmktimectime

mktime() for non-local timezone


In C the function mktime() returns the epoch time according to the local timezone (the input struct is locally formatted).

The function timegm() returns the epoch time according to the UTC time (the input struct is formatted based off of UTC time).

The function localtime_r () takes in an epoch time and returns a local timezone formatted struct.

The function gmtime_r () takes in an epoch time and returns a UTC formatted struct.

I need to find out if a non-local timezone is currently daylight savings time or not, which would work with the localtime_r() function if it were local, but what if it were not local?

The gmtime_r() function always sets the tm_isdst field to zero, which won't work here.

Maybe there's some other function I am not aware of. Not sure.


Solution

  • I need to find out if a non-local timezone is currently daylight savings time or not

    1. Get the current time as a time_t from time.
    2. Set env var TZ to the target time zone using putenv.
    3. Call tzset. (I don't know if this is required, but there's surely no harm in calling it.)
    4. Use localtime to convert the time_t into a struct tm according to the (modified) local time zone.
    5. Check the tm_isdst field of that struct tm.