Easy way to convert a struct tm (expressed in UTC) to time_t type

前端 未结 9 926
臣服心动
臣服心动 2020-11-29 05:44

How do I do the above? There is mktime function but that treats the input as expressed in local time but how do i perform the conversion if my input tm variable happens to b

9条回答
  •  -上瘾入骨i
    2020-11-29 06:32

    POSIX page for tzset, describes global variable extern long timezone which contains the local timezone as an offset of seconds from UTC. This will be present on all POSIX compliant systems.

    In order for timezone to contain the correct value, you will likely need to call tzset() during your program's initialization.

    You can then just add timezone to the output of mktime to get the output in UTC.

    #include 
    #include 
    #include 
    
    time_t utc_mktime(struct tm *t)
    {
        return mktime(t) + timezone;
    } 
    
    int main(int argc, char **argv)
    {
        struct tm t = { 0 };
    
        tzset();
        utc_mktime(&t);
    }
    

    Note: Technically tzset() and mktime() aren't guaranteed to be threadsafe.

    If a thread accesses tzname, [XSI] [Option Start] daylight, or timezone [Option End] directly while another thread is in a call to tzset(), or to any function that is required or allowed to set timezone information as if by calling tzset(), the behavior is undefined.

    ...but the majority of implementations are. GNU C uses mutexes in tzset() to avoid concurrent modifications to the global variables it sets, and mktime() sees very wide use in threaded programs without synchronization. I suspect if one were to encounter side effects, it would be from using setenv() to alter the value of TZ as done in the answer from @liberforce.

提交回复
热议问题