std::chrono::floor to daystart 在当前时区

问题描述 投票:0回答:0

我的问题是 std::chrono::floor 给了我 UTC 的开始时间,而不是我当地时区的开始时间。有解决办法吗?

比较这个:

演示

#include <time.h>
#include <cstdio>
#include <iostream>
#include <cstdint>
#include <chrono>
#include <ctime>

int main() {
    setenv("TZ", "CET-1CEST,M3.5.0,M10.5.0", 1);
    tzset();

    const auto tp_daystart = std::chrono::floor<std::chrono::days>(std::chrono::system_clock::now());
    const auto tp_now = std::chrono::system_clock::now();
    const auto daysec = std::chrono::duration_cast<std::chrono::seconds>(tp_now - tp_daystart);
    std::time_t ttp = std::chrono::system_clock::to_time_t(tp_now);
    std::time_t ttp_s = std::chrono::system_clock::to_time_t(tp_daystart);
    std::cout << "time start: " << std::ctime(&ttp_s) << " / time now: " << std::ctime(&ttp) << "seconds since start of day = " << daysec.count() << "\n";
}

这产生:

time start: Mon May  1 02:00:00 2023
 / time now: Mon May  1 16:26:04 2023
seconds since start of day = 51964

从一天开始的秒数当然是错误的,因为我确实想在这个时区计算从今天开始的秒数!我如何做到这一点?

c++ c++-chrono floor
© www.soinside.com 2019 - 2024. All rights reserved.