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

如何格式化std::chrono::utc_clock至毫秒精度且无末尾零?

解决C++ chrono时间格式化末尾多余零的问题

问题出在%T格式符会默认将秒的小数部分填充至纳秒位(即便你的时间点已转换为毫秒精度,仍会补零)。要去除末尾零,你需要明确指定只保留三位小数(对应毫秒精度),而非依赖%T的默认行为。

方法一:C++20 std::format 简洁实现

修改格式化字符串,直接指定毫秒位数:

std::stringstream s;
std::chrono::time_point<std::chrono::utc_clock> TimeTag = time_point_cast<std::chrono::milliseconds>(std::chrono::utc_clock::now());

// 明确指定毫秒部分为三位数字
s << format("{0:%FT%H:%M:%S.%3LZ}", TimeTag);

这样输出会变为 2024-01-07T17:02:50.214Z,完美去除末尾多余的零。

这里的%3L表示提取时间点的毫秒部分(固定三位数字),和你已转换的milliseconds精度完全匹配,不会产生补零。

方法二:兼容旧C++版本的手动拆分实现

如果你的编译器不支持C++20的chrono format特性,可以手动拆分秒与毫秒部分:

#include <iomanip> // 需包含此头文件使用setw、setfill

std::stringstream s;
std::chrono::time_point<std::chrono::utc_clock> TimeTag = time_point_cast<std::chrono::milliseconds>(std::chrono::utc_clock::now());

// 拆分秒和毫秒部分
auto ms_total = std::chrono::duration_cast<std::chrono::milliseconds>(TimeTag.time_since_epoch());
auto sec_total = std::chrono::duration_cast<std::chrono::seconds>(ms_total);
std::chrono::milliseconds ms_part = ms_total - sec_total;

// 格式化秒部分为UTC时间
std::time_t tt = std::chrono::utc_clock::to_time_t(TimeTag);
std::tm tm = *std::gmtime(&tt);
char buf[32];
std::strftime(buf, sizeof(buf), "%FT%H:%M:%S", &tm);

// 拼接毫秒部分,确保三位数字格式
s << buf << "." << std::setw(3) << std::setfill('0') << ms_part.count() << "Z";

std::setw和std::setfill用于保证毫秒部分始终是三位数字(比如1毫秒会显示为001)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:15:13