如何使用 C++20 中的格式打印毫秒

问题描述 投票:0回答:2

我有以下代码,我正在努力寻找声明性方式来做我想做的事情。

我希望将当前时间输出到毫秒精度(向下舍入也可以,例如 129999 us 可以舍入到 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++20 c++-chrono fmt
2个回答
3
投票
#include <fmt/chrono.h>

auto a = system_clock::now();
print("{:%FT%T%Oz}\n", a);
print("{0:%FT%H:%M:}{1:%S}{0:%Oz}\n", a,a.time_since_epoch());

打印

2021-04-13T21:38:04+0800
2021-04-13T21:38:04.076+0800

2
投票

您可以通过将持续时间转换为

std::chrono::milliseconds
并使用
%S
来完成此操作。例如:

#include <fmt/chrono.h>

int main() {
  auto d = std::chrono::system_clock::now().time_since_epoch();
  fmt::print("{:%S}",
             std::chrono::duration_cast<std::chrono::milliseconds>(d));
}

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

34.459

上帝闪电:https://godbolt.org/z/hannve7eK

© www.soinside.com 2019 - 2024. All rights reserved.