You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++20中使用std::chrono::parse解析GMT+-H格式

解决std::chrono解析"GMT+N"格式时区的问题

你不需要分开解析日期时间和时区,直接用std::chrono::from_stream配合简单的手动匹配就能处理2022-07-10 22:00 GMT+2这种格式,核心原因是标准格式符不兼容GMT+2的写法:

  • %z仅支持±HHMM(比如+0200)这种四位数字的时区偏移,而GMT+2是文字前缀加一位/两位数字,所以直接用%F %T GMT%z会失败
  • 可以拆分解析逻辑:先解析日期时间部分,再提取时区偏移值并调整时间点

下面是可运行的代码示例:

#include <chrono>
#include <iostream>
#include <sstream>
#include <string>

int main() {
    const std::string time_str = "2022-07-10 22:00 GMT+2";
    std::istringstream iss(time_str);
    
    std::chrono::sys_seconds utc_time;
    std::string tz_tag;
    int offset_hours;
    
    // 解析日期时间(注意%T后面的空格,匹配字符串里的空格)
    if (iss >> std::chrono::parse("%F %T ", utc_time) >> tz_tag >> offset_hours) {
        if (tz_tag == "GMT") {
            // 原时间是GMT+2时区的本地时间,转换为UTC需要减去偏移小时
            utc_time -= std::chrono::hours(offset_hours);
            std::cout << "UTC时间:" 
                      << std::chrono::format("%F %T", utc_time) << std::endl;
            // 输出结果:2022-07-10 20:00
        }
    } else {
        std::cerr << "解析失败" << std::endl;
    }
    return 0;
}
  • 解析时%F %T 的末尾空格很关键,用来匹配字符串中时间和GMT之间的空格
  • 如果你的场景中还会出现GMT-3、GMT+10这类格式,代码无需修改,int类型会自动处理正负值
  • 要是你需要将解析后的时间转换为本地时区,可以用std::chrono::current_zone()->to_local(utc_time)来处理

内容的提问来源于stack exchange,提问作者fen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:17:19