2012-07-13 38 views
3

我用下面的代碼段來計算UTC偏移量如何獲得UTC偏移,但我知道有時候它返回錯誤的結果:在Linux中使用C++

double DateTime::getUTCOffset() 
{ 
    time_t currtime; 

    struct tm * timeinfo; 



    time (&currtime); 

    timeinfo = gmtime (&currtime); 

    time_t utc = mktime(timeinfo); 

    timeinfo = localtime (&currtime); 

    time_t local = mktime(timeinfo); 



    // Get offset in hours from UTC 

    double offsetFromUTC = ((difftime(local, utc)/HOUR_IN_SECONDS)); 

    // Adjust for DST 

    if (timeinfo->tm_isdst) 
    { 
     offsetFromUTC += 1; 
    } 
    return offsetFromUTC; 
} 

%的它是正確的,雖然時間90,什麼是計算utc偏移量的最佳方法是什麼?

+1

相關:如何使用Boost DateTime獲取UTC偏移量:http://stackoverflow.com/questions/3854496/how-do-i-get-the-current-utc-offset-time-zone – 2012-07-13 12:24:43

回答

5

我認爲tm_gmtoff字段應該在你的系統上可用。

std::time_t current_time; 
std::time(&current_time); 
struct std::tm *timeinfo = std::localtime(&current_time); 
long offset = timeinfo->tm_gmtoff;