gpt4 book ai didi

c++ - 在Boost中解析RFC3339/ISO 8601时间戳

转载 作者:行者123 更新时间:2023-12-01 19:02:14 26 4
gpt4 key购买 nike

如何解析 RFC3339 C++03 中的时间戳(“1985-04-12T23:20:50.52Z”)(即 ISO8601 的子集)?我正在使用 Boost,但 Boost 日期时间库似乎都不包含执行此操作的函数。

实际时间对象的类型并不重要,只要我可以轻松地将它与“现在”进行比较即可。我只关心 UTC 时区的时间戳。

最佳答案

解析时区有限制。

#include <sstream>
#include <iostream>
#include <string>
#include <iomanip>

int main() {
std::tm t = {};
std::string s = "2016-01-02T15:04:05+09:00";
int tz_offset = 0;
auto pos = s.find_last_of("+-Z");
if (pos != s.npos) {
std::string zone = s.substr(pos);
tz_offset = std::atoi(zone.c_str());
s.resize(pos);
}
std::stringstream ss(s);
ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S");
if (ss.fail()) {
std::cout << "Parse failed\n";
} else {
std::time_t l = std::mktime(&t);
std::tm tm_utc(*std::gmtime(&l));
std::time_t utc = std::mktime(&tm_utc);
tz_offset += (utc - l);
l = std::mktime(&t) - tz_offset;
t = *std::gmtime(&l);
std::cout << std::put_time(&t, "%c") << std::endl;
}
}

关于c++ - 在Boost中解析RFC3339/ISO 8601时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44843416/

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