【问题标题】:how to get utc offset in linux using c++如何使用 C++ 在 linux 中获取 UTC 偏移量
【发布时间】:2012-07-13 06:30:56
【问题描述】:

我使用以下代码段来计算 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 偏移量的最佳方法是什么?

【问题讨论】:

标签: c++ debian utc


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2012-02-27
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多