std::mktime and timezone info

后端 未结 12 502
忘了有多久
忘了有多久 2020-11-30 10:56

I\'m trying to convert a time info I reveive as a UTC string to a timestamp using std::mktime in C++. My problem is that in / &

12条回答
  •  自闭症患者
    2020-11-30 11:24

    If you are trying to do this in a multithreaded program and don't want to deal with locking and unlocking mutexes (if you use the environment variable method you'd have to), there is a function called timegm that does this. It isn't portable, so here is the source: http://trac.rtmpd.com/browser/trunk/sources/common/src/platform/windows/timegm.cpp

    int is_leap(unsigned y) {
        y += 1900;
        return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0);
    }
    
    time_t timegm (struct tm *tm)
    {
        static const unsigned ndays[2][12] = {
            {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
            {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
        };
        time_t res = 0;
        int i;
    
        for (i = 70; i < tm->tm_year; ++i)
            res += is_leap(i) ? 366 : 365;
    
        for (i = 0; i < tm->tm_mon; ++i)
            res += ndays[is_leap(tm->tm_year)][i];
        res += tm->tm_mday - 1;
        res *= 24;
        res += tm->tm_hour;
        res *= 60;
        res += tm->tm_min;
        res *= 60;
        res += tm->tm_sec;
        return res;
    }
    

提交回复
热议问题