4

我正在使用以下代码段来计算 utc 偏移量,但我意识到有时它会返回错误的结果:

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 偏移量的最佳方法是什么?

4

1 回答 1

7

我认为该tm_gmtoff字段应该在您的系统上可用。

std::time_t current_time;
std::time(&current_time);
struct std::tm *timeinfo = std::localtime(&current_time);
long offset = timeinfo->tm_gmtoff;
于 2012-07-13T12:21:37.597 回答