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

后端 未结 5 2386
不思量自难忘°
不思量自难忘° 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:08

    I would like to submit yet another answer to this question, one that AFAICS also deals with the IDL.

    This solution depends on timegm and mktime. On Windows timegm is available as _mkgmtime from the CRT, in other words define a conditional macro.

    #if _WIN32
    #    define timegm _mkgmtime
    #endif
    
    int local_utc_offset_minutes ( ) {
        time_t t  = time ( NULL );
        struct tm * locg = localtime ( &t );
        struct tm locl;
        memcpy ( &locl, locg, sizeof ( struct tm ) );
        return (int)( timegm ( locg ) - mktime ( &locl ) ) / 60;
    }
    

提交回复
热议问题