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

前端 未结 9 887
臣服心动
臣服心动 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条回答
  • 2020-11-29 06:42

    The answer of Loki Astari was a good start, timegm is one of the possible solutions. However, the man page of timegm gives a portable version of it, as timegm is not POSIX-compliant. Here it is:

    #include <time.h>
    #include <stdlib.h>
    
    time_t
    my_timegm(struct tm *tm)
    {
        time_t ret;
        char *tz;
    
        tz = getenv("TZ");
        if (tz)
            tz = strdup(tz);
        setenv("TZ", "", 1);
        tzset();
        ret = mktime(tm);
        if (tz) {
            setenv("TZ", tz, 1);
            free(tz);
        } else
            unsetenv("TZ");
        tzset();
        return ret;
    }
    
    0 讨论(0)
  • 2020-11-29 06:45

    The following implementation of timegm(1) works swimmingly on Android, and probably works on other Unix variants as well:

    time_t timegm( struct tm *tm ) {
      time_t t = mktime( tm );
      return t + localtime( &t )->tm_gmtoff;
    }
    
    0 讨论(0)
  • 2020-11-29 06:46

    I was troubled by the issue of mktime() as well. My solution is the following

    time_t myTimegm(std::tm * utcTime)
    {
        static std::tm tmv0 = {0, 0, 0, 1, 0, 80, 0, 0, 0};    //1 Jan 1980
        static time_t utcDiff =  std::mktime(&tmv0) - 315532801;
    
        return std::mktime(utcTime) - utcDiff;
    }
    

    The idea is to get the time difference by calling std::mktime() with a known time (in this case 1980/01/01) and subtract its timestamp (315532801). Hope it helps.

    0 讨论(0)
提交回复
热议问题