gpt4 book ai didi

c++ clock_gettime() 和夏令时

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:55:01 24 4
gpt4 key购买 nike

我在我的 C++ 程序中使用 clock_gettime() 来获取当前时间。但是,返回值是自 UTC 纪元以来的秒数。在夏令时期间,当时间偏移一小时时,此代码在我的时区可能会搞砸。

系统本身有 NTP 同步它总是在 EST 中给出正确的时间。有没有办法让 clock_gettime() 报告本地时间而不是 UTC,这样我就可以避免夏令时问题?

最佳答案

意识到 time 还报告自 1970 年初以来的秒数(在 time_t 中)。如果你获取 timespectv_sec 成员并将其传递给 localtimelocaltime_r,你应该得到你想要的想要。

timespec tsv;
clock_gettime(CLOCK_REALTIME, &tsv);
time_t t = tsv.tv_sec; // just in case types aren't the same
tm tmv;
localtime_r(&t, &tmv); // populate tmv with local time info

您可以随心所欲地处理 timespectv_nsec 成员。

关于c++ clock_gettime() 和夏令时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11127538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com