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

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

    This C code computes the local time offset in minutes relative to UTC. It assumes that DST is always one hour offset.

    #include 
    #include 
    
    int main()
    {
        time_t rawtime = time(NULL);
        struct tm *ptm = gmtime(&rawtime);
        time_t gmt = mktime(ptm);
        ptm = localtime(&rawtime);
        time_t offset = rawtime - gmt + (ptm->tm_isdst ? 3600 : 0);
    
        printf("%i\n", (int)offset);
    }
    

    It uses gmtime and localtime though. Why don't you want to use those functions?

提交回复
热议问题