c++ - 如何在C++ 20中使用格式打印毫秒

标签 c++ c++20 chrono fmt

我有以下code,我正在努力获取声明性方式来做自己想要的事情。
我想将当前时间输出到ms精度(四舍五入也很好,例如129999 us可以四舍五入为129ms,但在这种情况下我更喜欢130)。
注意:我正在使用fmt,因为从我看到的<format> header 来看,它仍未实现。

#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
Godbolt:https://godbolt.org/z/Y1jzv5

关于c++ - 如何在C++ 20中使用格式打印毫秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63829143/

相关文章:

c++ - 为什么 `constexpr` 函数在编译时和运行时会产生不同的结果?

c++ - 如何将 std::tuple 转换为 std::any?

c++ - C++中的非虚拟指针?

c++ - boost::date_time 和 std::chrono 之间的互操作性

c++ - 为什么在堆中创建对象或堆栈中的临时对象时,隐式构造函数将结构中的 POD 初始化为零?

c++ - 你为什么要在 C++ 中创建一个指向原始类型的唯一指针?

C++ 在模板中使用运算符关键字?

c++ - MFC:GetWindowRect 用法

c++ - 使用 std::chrono 在 C++ 中输出日期和时间

c++ - std::system_clock 和 std::steady_clock 之间的区别?