bsguru
bsguru

Reputation: 472

How to calculate UTC offset from IANA timezone name in C

I have timezone names like Europe/Paris , America/New_York as described in
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Given these strings (like "Europe/Paris") I want to know the UTC offset in seconds for these timezones.

One way I can think of is play with TZ environment variables to set timezone and calculate offset.But I am able to figure out exactly how to do this.

I am working in C on linux.

Need your suggestions!

Upvotes: 0

Views: 1128

Answers (1)

Marian
Marian

Reputation: 7472

I am using the following code to get time with a specific timezone.

time_t mkTimeForTimezone(struct tm *tm, char *timezone) {
    char        *tz;
    time_t      res;

    tz = getenv("TZ");
    if (tz != NULL) tz = strdup(tz);
    setenv("TZ", timezone, 1);
    tzset();
    res = mktime(tm);
    if (tz != NULL) {
        setenv("TZ", tz, 1);
        free(tz);
    } else {
        unsetenv("TZ");
    }
    tzset();
    return(res);
}

Using this function the calculation of the offset is strait-forward. For example:

int main() {
    char      *timezone = "America/New_York";
    struct tm tt;
    time_t    t;
    int       offset;

    t = time(NULL);
    tt = *gmtime(&t);
    offset =  mkTimeForTimezone(&tt, timezone) - t;
    printf("Current offset for %s is %d\n", timezone, offset);
}

Upvotes: 2

Related Questions