【问题标题】:How to print milliseconds using format in C++20如何在 C++20 中使用格式打印毫秒
【发布时间】:2020-12-28 22:03:57
【问题描述】:

我有以下code,如果我正在努力获得声明式的方式来做我想做的事。

我希望将当前时间输出到 ms 精度(向下舍入也可以,例如 129999 我们可以舍入到 129ms,但在这种情况下我更喜欢 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 chrono fmt


【解决方案1】:

%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

【讨论】:

  • 有趣的是,%T 实际上并不意味着 %H:%M:%S,而是在 seconds 中打印?
  • 不确定这个答案是否正确,请看:godbolt.org/z/fKsz6e
  • 也许问题是我正在使用 std::chrono::sys_time ?
  • sys_time 格式是最近的贡献,可能不完整。
  • 可能。 {fmt} 应该按照标准对计时格式的规定做任何事情。
【解决方案2】:
#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

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2010-12-22
    • 2013-04-22
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2012-09-09
    • 2023-03-22
    相关资源
    最近更新 更多