C时间API的使用对于您的用例来说可能非常令人困惑,因为它涉及到本地时区之间的转换,这是完全不必要的复杂情况。
Fwiw,我已经根据下面的date.h标题重写了您的转换函数:
uint64_t
from_isoTimeString(std::string iso_time_string)
{
//--- takes an UTC ISO formatted time/date string and converts it to a timestamp value
date::sys_seconds tmb;
std::stringstream ss(iso_time_string);
ss >> date::parse("%Y-%m-%dT%TZ", tmb);
if (ss.fail())
{
std::string errmsg = "unable to convert Timestamp '" + iso_time_string + "' from ISO 8601 format";
throw std::invalid_argument(errmsg);
}
return static_cast<uint64_t>(tmb.time_since_epoch().count());
}
std::string
formatTimestamp(uint64_t epoch_seconds, std::string timestamp_format)
{
date::sys_seconds tt{std::chrono::seconds{epoch_seconds}};
std::stringstream ss;
ss << date::format(timestamp_format, tt);
if (ss.fail())
{
std::string err_msg = "unable to convert Timestamp to " + timestamp_format + " format";
throw std::invalid_argument(err_msg);
}
return ss.str();
}
我在每个功能中都尽可能少地进行更改。现在您的本地时区不是计算的一部分。这段代码将很容易地移植到C++20(如果可用),只需更改几个
date::
到
std::chrono::
或
std::
.
你的
main()
根本不需要更改,现在的输出是:
time1_str: 2022-06-27T12:00:10Z
time1_uint as string: 2022-06-27T12:00:10Z
time1_uint: 1656331210
time1_str from string: 1656331210