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

标签 c++ boost iso8601 rfc3339

如何解析 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/

相关文章:

c++ - 指向嵌套结构中成员变量的指针

iso8601 - ISO8601 持续时间 'months' 和 'years' 有多少天?

ios - 如何在 iOS 上获取 ISO 8601 日期?

c++ - 如何在 Windows 映射我的程序的 DLL 之前保留内存区域?

c++ - Boost::DateTime 无法正确解析

c++ - 使用模板打印一个类

c++ - 将模板化类型作为字符串获取

java - 在 Time4j 中迭代给定范围的重复时间戳

c++ - 无法连接QT信号

c++ - 服务器证书验证失败。 CAfile : ca. pem CRL 文件:无