【问题标题】:Why does std::localtime give varying offset from UTC?为什么 std::localtime 会给出与 UTC 不同的偏移量?
【发布时间】:2021-03-13 18:03:05
【问题描述】:

我在英国,所以我的时区目前与 UTC 相同。在下面的代码中,如果我将不同的时间戳传递给本地时间,我会得到与 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

【问题讨论】:

  • 你知道夏季和冬季时间,过去可能的时区变化吗?
  • 我认为Tom Scott video 在这里非常合适。
  • 是的,当然,但我不明白为什么应该改变本地时间的表示。我的时区(或 DST)在程序执行过程中没有改变。
  • @WillPlatts:但您询问的是英国时区 在不同时间点的 UTC 偏移量。 运行代码时的 UTC 偏移量无关紧要。
  • @Casey 我去看看!

标签: c++ date timezone


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-07-20
    • 1970-01-01
    • 2016-11-21
    • 2016-07-19
    • 1970-01-01
    • 2017-05-26
    • 2011-03-01
    • 1970-01-01
    相关资源
    最近更新 更多