我有一些使用 Howard Hinnant's date Library 的代码解析启用微秒的时间戳:
std::string time_test = "13:45:04.747334";
std::istringstream input(time_test);
std::chrono::microseconds current_time;
input >> date::parse("%T", current_time);
这会产生自午夜以来的微秒数,但假设为微秒数。
现在我需要将其添加到今天本地午夜自纪元以来的微秒数,但库假设 std::chrono::system_clock::now()
提供 UTC 时间。
如何获取自纪元以来的时间计算为本地时间?
最佳答案
要处理本地时间,您需要 install the "date/tz.h"
library 。这涉及编译一个源文件:tz.cpp,并允许自动下载 IANA 时区数据库、自行手动安装或使用操作系统的拷贝(如果可用)。
获取当前本地时间的最简单方法是组合 system_clock::now()
与 current_zone()
在一个名为 zoned_time
的对象中:
zoned_time zt{current_zone(), system_clock::now()};
current_zone()
返回 time_zone const*
代表您的计算机当前设置的本地时区的时区。来自 zoned_time
您可以获得本地时间:
auto local_tp = zt.get_local_time();
local_tp
是 chrono::time_point
,但从 system_clock::time_point
偏移按您所在时区的当前 UTC 偏移量。然后您可以使用local_tp
就像您可能使用 system_clock::time_point
一样。例如,要获取当天的本地时间:
auto tod = local_tp - floor<days>(local_tp);
tod
只是一个 chrono::duration
测量自本地午夜以来的时间。
或者如果你有这样的持续时间,比如 current_time
您在问题中进行了解析,您可以将其添加到本地午夜:
auto tp = floor<days>(local_tp) + current_time;
在这里,tp
类型为 local_time<microseconds>
。和local_time<duration>
只是 chrono::time_point<local_t, duration>
的类型别名.
How do get time since epoch calculated as local time?
这是一个有点模棱两可的问题,所以我没有直接回答它。不过,如果您能澄清这个问题,我很乐意尝试。纪元为 1970-01-01 00:00:00 UTC,自该时刻以来的持续时间与任何时区无关。
为了进一步详细说明,给定当前本地时间( current_time
)并假设我们知道本地日期(例如 2020-12-16),我们可以形成一个 zoned_time
封装了本地时间和 UTC 等效时间:
string time_test = "19:45:04.747334";
istringstream input(time_test);
chrono::microseconds current_time;
input >> date::parse("%T", current_time);
local_days today{2020_y/12/16};
zoned_time zt{current_zone(), today + current_time};
cout << format("%F %T %Z\n", zt);
cout << format("%F %T %Z\n", zt.get_sys_time());
输出:
2020-12-16 19:45:04.747334 EST
2020-12-17 00:45:04.747334 UTC
关于C++ 时区偏移到解析时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65332583/