c++ - 如何在 C++20 中使用格式打印毫秒
问题描述
我有以下代码,我正在努力获得做我想做的声明的方式。
我希望将当前时间输出到毫秒精度(四舍五入也可以,例如 129999 我们可以四舍五入到 129 毫秒,但在这种情况下我更喜欢 130)。
注意:我正在使用 fmt ,因为从我看到<format>
的标题中仍然没有实现。
#include<string>
#include<chrono>
#include<iostream>
#include<thread>
#include<fmt/format.h>
#include<fmt/chrono.h>
using namespace std::chrono;
int main(){
for (int i =0; i<5;++i){
// I wish this was local_time, not sys time, and that sys_time<milliseconds> worked
const std::chrono::sys_time<nanoseconds> now =
(std::chrono::system_clock::now());
auto round_now = std::chrono::round<milliseconds>(now);
int64_t ms = (round_now.time_since_epoch()%seconds(1)).count();
// %S does not print milliseconds
std::cout << fmt::format("{:%F %H:%M:%S}.{:03}", now, ms) << std::endl;
std::cout << std::endl;
std::this_thread::sleep_for(milliseconds(100));
}
std::cout << "Bye";
}
解决方案
%S
默认打印毫秒。例如:
#include <fmt/chrono.h>
int main() {
fmt::print("{:%S}", std::chrono::system_clock::now().time_since_epoch());
}
打印(实际输出当然取决于当前时间):
34.459
推荐阅读
- django - 当用户在 django 中注册时如何触发功能?
- c# - 为什么 Marshal.SizeOf<>() 为结构或类提供不同的大小?
- c# - 在按值日期时间排序的字典中获取值?
- html - 有没有办法模仿
- android - 试图在我的手机上安装一个简单的 kivy 应用程序,但收到 buildozer last 命令错误消息
- android - 为什么我的应用程序被检测为病毒?它发生在更新 SDK 版本和 Adsense 之后
- python - 检查python中排列的有效性
- php - Moodle 1.8.1 PHP 问题
- html - 我想从名为“se_component_wrap sect_dsc __se_component_area”的特定 div 类中提取 html
- logic - 如何将 Coq 用作计算器或前向链接规则引擎/序列应用工具?