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

C++20 Linux环境下将指定格式UTC字符串转为UNIX时间戳

在Linux环境下用C++20将UTC时间字符串转为UNIX时间戳的标准实现

针对格式为"2024-04-26T14:33:30.185Z"的UTC时间字符串,C++20标准库的<chrono>模块提供了简洁高效的原生实现,无需依赖第三方库或旧标准API。以下是适配Linux环境的实现方案:

核心思路

利用C++20新增的std::chrono::from_stream解析时间字符串,直接转换为std::chrono::system_clock对应的时间点(sys_time),再计算该时间点距离UNIX纪元(1970-01-01 00:00:00 UTC)的时长,得到数值型时间戳。

完整代码示例

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

int main() {
    const std::string time_str = "2024-04-26T14:33:30.185Z";
    
    // 解析为带毫秒精度的UTC系统时间点
    std::chrono::sys_time<std::chrono::milliseconds> tp;
    std::istringstream iss(time_str);
    iss >> std::chrono::from_stream("%Y-%m-%dT%H:%M:%S.%LZ", tp);
    
    if (iss.fail()) {
        std::cerr << "时间字符串解析失败" << std::endl;
        return 1;
    }
    
    // 转换为毫秒级UNIX时间戳
    auto timestamp_ms = tp.time_since_epoch().count();
    // 若需要秒级时间戳,可转换为秒精度:
    // auto timestamp_s = std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch()).count();
    
    std::cout << "毫秒级时间戳: " << timestamp_ms << std::endl;
    return 0;
}

关键细节说明

  • 格式字符串:"%Y-%m-%dT%H:%M:%S.%LZ"完全匹配输入格式,其中%LZ专门用于识别UTC时间的Z后缀。
  • 时间精度:示例中使用std::chrono::milliseconds对应输入的三位毫秒,若需要更高/更低精度,可替换为microseconds、seconds等。
  • sys_time的意义:std::chrono::sys_time直接映射到系统时钟(Linux下即UNIX时间),无需额外时区转换,符合需求中"无需时区转换"的要求。
  • 编译要求:需启用C++20标准编译,例如GCC使用g++ -std=c++20 your_file.cpp。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:52:39