Confused by C++ chrono zoned_time's get_sys_time and get_local_time

55 Views Asked by At

I am using GCC 13.2.0. My local time zone is PST. I am trying std::chrono::zoned_time and confused by its get_sys_time and get_local_time.

#include <iostream>
#include <chrono>
#include <iomanip>

int main() {
    using namespace std::chrono;

    std::cout << "sys " << zoned_time{current_zone(), system_clock::now()}.get_sys_time().time_since_epoch() << '\n'
              << "local " << zoned_time{current_zone(), system_clock::now()}.get_local_time().time_since_epoch() << std::endl;

    return 0;
}

My local time is Feb 25, 20024, around 5:35 PM. The code above gives: sys 1708911328957330000ns local 1708882528957347000ns

I thought get_local_time should give me the right duration since local epoch. But get_sys_time actually gives me right answer. I am wondered if I misunderstand those two methods. Thank you.

The above code confused me.

1

There are 1 best solutions below

0
Howard Hinnant On

The relationship between local_time and sys_time is:

local_time - sys_time == UTC offset

For you that looks like -8h, which checks out.

sys_time tp{1708911328957330000ns};
local_time tp_local{tp.time_since_epoch() + -8h};
std::cout << tp << " UTC\n";
std::cout << tp_local << " PST\n";

Output:

2024-02-26 01:35:28.957330000 UTC
2024-02-25 17:35:28.957330000 PST