首页 > 解决方案 > 如何在 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";
}

标签: c++c++20chronofmt

解决方案


%S默认打印毫秒。例如:

#include <fmt/chrono.h>

int main() {
  fmt::print("{:%S}", std::chrono::system_clock::now().time_since_epoch());
}

打印(实际输出当然取决于当前时间):

34.459

神箭:https ://godbolt.org/z/Y1jzv5


推荐阅读