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

如何使用std::formatter为std::chrono::sys_time指定精度去除小数部分

解决std::format格式化时间时去除秒小数部分的问题

要去掉格式化后时间末尾的小数部分,有两种简单可靠的方法:

方法一:显式指定时分秒格式,替代%T

%T是预定义的格式组合,等价于%H:%M:%S.%f(包含秒的小数部分)。直接改用%H:%M:%S就能只输出时分秒,不包含小数:

#include <chrono>
#include <format>
#include <iostream>
 
int main()
{
    auto time = std::chrono::system_clock::now();
    std::cout << std::format("Current time is '{0:%H:%M:%S}'.", time) << '\n';    
}

运行后输出示例:

Current time is '11:47:50'.

方法二:将时间点截断到秒精度

把当前时间点转换为以秒为单位的精度,这样即使使用%T格式化,也不会出现小数部分:

#include <chrono>
#include <format>
#include <iostream>
 
int main()
{
    auto time = std::chrono::system_clock::now();
    // 向下取整到最近的秒
    auto time_sec = std::chrono::floor<std::chrono::seconds>(time);
    std::cout << std::format("Current time is '{0:%T}'.", time_sec) << '\n';    
}

为什么{0:.0%T}无效?

%T作为预定义的组合格式,它的结构是固定的%H:%M:%S.%f。你尝试的.0精度说明无法作用于这个组合格式的小数部分——这种精度写法只对单个格式符(比如%f)或数值类型生效,对预定义的时间格式组合不适用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 16:09:51