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

在C++中将Unix微秒时间转换为ISO 8601格式字符串

将微秒级Unix时间转换为ISO 8601格式字符串

要把microsecondsUnixTime(64位有符号整数,存储微秒级Unix时间)转换为ISO 8601格式的字符串,可以通过以下步骤实现:

核心思路

  1. 将微秒数转回std::chrono::system_clock的时间点
  2. 拆分出秒级时间和剩余的微秒部分
  3. 用字符串流格式化秒级时间为ISO 8601基础格式,再追加微秒和时区标识

完整代码实现

首先确保包含必要的头文件:

#include <chrono>
#include <string>
#include <iomanip>
#include <sstream>
#include <ctime>

然后实现转换函数:

std::string microseconds_to_iso8601(int64_t microsecondsUnixTime) {
    // 把微秒数转换为system_clock时间点
    std::chrono::microseconds us_duration(microsecondsUnixTime);
    std::chrono::system_clock::time_point time_point = 
        std::chrono::time_point_cast<std::chrono::system_clock::duration>(us_duration);
    
    // 提取秒级时间
    std::time_t seconds_time = std::chrono::system_clock::to_time_t(time_point);
    
    // 计算剩余的微秒部分(确保6位补零)
    int microsec_part = static_cast<int>(microsecondsUnixTime % 1000000);
    
    // 格式化字符串
    std::ostringstream oss;
    // 格式化秒级部分为YYYY-MM-DDTHH:MM:SS(UTC时间)
    oss << std::put_time(std::gmtime(&seconds_time), "%Y-%m-%dT%H:%M:%S");
    // 追加微秒和UTC时区标识Z
    oss << '.' << std::setw(6) << std::setfill('0') << microsec_part << 'Z';
    
    return oss.str();
}

关键细节说明

  • 使用std::gmtime而非std::localtime,确保输出UTC时间(符合ISO 8601规范,用Z标识时区),如果需要本地时间可替换为std::localtime并追加对应时区偏移
  • 微秒部分通过取余计算,并用std::setw(6)和std::setfill('0')保证始终是6位,避免出现类似123这样的短格式
  • std::put_time是C11引入的特性,需要编译器支持C11及以上标准
  • std::chrono::system_clock的epoch与Unix epoch(1970-01-01T00:00:00Z)一致,无需额外偏移

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:40:19