Why does std::localtime give varying offset from UTC?

I am in the UK, so my timezone is currently the same as UTC. In the following code, if I pass different timestamps to localtime, I get different offsets from UTC (via gmtime). Why is this? My timezone isn’t changing from call to call, so I didn’t expect the offset to be affected by the timestamp given.

#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;
}

Output:

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

Answer

The UK observes daylight savings time, switching to British Summer Time in the summer. Hence, if you pass in a timestamp that falls within the part of the year when British Summer Time is in effect, you will see that your local time is one hour ahead of UTC.

Leave a Reply

Your email address will not be published. Required fields are marked *