微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么 std::localtime 会给出与 UTC 不同的偏移量?

如何解决为什么 std::localtime 会给出与 UTC 不同的偏移量?

我在英国,所以我的时区目前与 UTC 相同。在下面的代码中,如果我将不同的时间戳传递给 localtime,我会从 UTC 获得不同的偏移量(通过 gmtime)。为什么是这样?我的时区不会因调用而改变,所以我没想到偏移量会受到给定时间戳的影响。

#include <ctime>
#include <iostream>

int main()
{
    for (time_t t = 0; t < 300000000; t+=10000000)
    {
        std::tm *timeInfo;

        // Get UTC time
        timeInfo = std::gmtime(&t);
        auto gm_hours = timeInfo->tm_hour;

        // Get localtime
        timeInfo = std::localtime(&t);

        // Print offset from UTC
        std::cout << "Timestamp: " << t << " Hours ahead of UTC : " << (timeInfo->tm_hour - gm_hours) << std::endl;
    }

    return 0;
}

输出

Timestamp: 0 Hours ahead of UTC : 1
Timestamp: 10000000 Hours ahead of UTC : 1
Timestamp: 20000000 Hours ahead of UTC : 1
Timestamp: 30000000 Hours ahead of UTC : 1
Timestamp: 40000000 Hours ahead of UTC : -23
Timestamp: 50000000 Hours ahead of UTC : 1
Timestamp: 60000000 Hours ahead of UTC : 0
Timestamp: 70000000 Hours ahead of UTC : 1
Timestamp: 80000000 Hours ahead of UTC : 1
Timestamp: 90000000 Hours ahead of UTC : 0
Timestamp: 100000000 Hours ahead of UTC : 0
Timestamp: 110000000 Hours ahead of UTC : 1
Timestamp: 120000000 Hours ahead of UTC : 1
Timestamp: 130000000 Hours ahead of UTC : 0
Timestamp: 140000000 Hours ahead of UTC : 1
Timestamp: 150000000 Hours ahead of UTC : 1
Timestamp: 160000000 Hours ahead of UTC : 0
Timestamp: 170000000 Hours ahead of UTC : 1
Timestamp: 180000000 Hours ahead of UTC : 1
Timestamp: 190000000 Hours ahead of UTC : 0
Timestamp: 200000000 Hours ahead of UTC : 1
Timestamp: 210000000 Hours ahead of UTC : 1
Timestamp: 220000000 Hours ahead of UTC : 0
Timestamp: 230000000 Hours ahead of UTC : 1
Timestamp: 240000000 Hours ahead of UTC : 1
Timestamp: 250000000 Hours ahead of UTC : 0
Timestamp: 260000000 Hours ahead of UTC : 1
Timestamp: 270000000 Hours ahead of UTC : 1
Timestamp: 280000000 Hours ahead of UTC : 0
Timestamp: 290000000 Hours ahead of UTC : 0

解决方法

英国实行夏令时,在夏季改用英国夏令时。因此,如果您传入一个属于英国夏令时生效年份的时间戳,您将看到您的当地时间比 UTC 早一小时。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。