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

前端 未结 9 927
臣服心动
臣服心动 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: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.

提交回复
热议问题