C code to get local time offset in minutes relative to UTC?

后端 未结 5 2351
不思量自难忘°
不思量自难忘° 2021-02-20 07:40

I didn\'t find a trivial way to get the time offset in minutes between the local time and the UTC time.

At first I intended to use tzset() but it doesn\'t p

5条回答
  •  温柔的废话
    2021-02-20 08:13

    IMHO the only foolproof and portable way is to use localtime and gmtime and manually compute the delta in minute because those 2 functions exist on all known systems. For example:

    int deltam() {
        time_t t = time(NULL);
        struct tm *loc = localtime(&t);
        /* save values because they could be erased by the call to gmtime */
        int loc_min = loc->tm_min;
        int loc_hour = loc->tm_hour;
        int loc_day = loc->tm_mday;
        struct tm *utc = gmtime(&t);
        int delta = loc_min - utc->tm_min;
        int deltaj = loc_day - utc->tm_mday;
        delta += (loc_hour - utc->tm_hour) * 60;
        /* hack for the day because the difference actually is only 0, 1 or -1 */
        if ((deltaj == 1) || (deltaj < -1)) {
            delta += 1440;
        }
        else if ((deltaj == -1) || (deltaj > 1)) {
            delta -= 1440;
        }
        return delta;
    }
    

    Beware, I did not test all possible corner cases, but it could be a starting point for your requirement.

提交回复
热议问题