How to calculate UTC offset from IANA timezone name in C

我的未来我决定 提交于 2019-12-12 02:54:59

问题


I have timezone names like Europe/Paris , America/New_York as described in
http://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!


回答1:


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);
}


来源:https://stackoverflow.com/questions/26845638/how-to-calculate-utc-offset-from-iana-timezone-name-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!