Mic*_*l A 9 c++ formatting c++-chrono c++20 fmt
我正在尝试将std::chrono::duration对象格式化为 HH:MM::SS 格式,例如 16:42:02 是小时 (16)、分钟 (42) 和秒 (2)。
该库fmt为此提供了有用的格式说明符:
using namespace std::chrono;
auto start = high_resolution_clock::now();
auto end = start + 4s;
fmt::print("{:%H:%M:%S} \n", end);
Run Code Online (Sandbox Code Playgroud)
不幸的是,它以小数形式打印秒
16:58:55.359425076
Run Code Online (Sandbox Code Playgroud)
我想将其四舍五入到最接近的整数,但无法弄清楚在哪里放置精度说明符(精度 2 仅在测试方面):
fmt::print("{:.2%H:%M:%S} \n", end); // error
fmt::print("{:.2f%H:%M:%S} \n", end); // error
fmt::print("{:%H:%M:.2%S} \n", end); // nonsense: 17:07:.202.454873454
Run Code Online (Sandbox Code Playgroud)
我盯着chrono 格式规范的细节有点迷失......
上面的编译器资源管理器示例在这里。
How*_*ant 13
要四舍五入到最接近的秒,请使用 将时间点转换为秒精度round<seconds>(tp)。此外,high_resolution_clock与日历没有可移植关系。你需要用system_clock它来代替。对于 gcc,high_resolution_clock是 的类型别名system_clock,因此它是偶然起作用的。但是使用 MSVC 或 LLVM 工具将无法编译。
#include <fmt/chrono.h>
#include <fmt/format.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
int main() {
using namespace std::chrono;
auto start = round<seconds>(system_clock::now());
auto end = start + 4s;
fmt::print("{:%H:%M:%S} \n", end);
}
Run Code Online (Sandbox Code Playgroud)
如果您想要其他舍入模式,也可以使用floor或ceil。