【问题标题】:How to get hh:mm:ss.uuuuuu timestamp in c++?如何在 C++ 中获取 hh:mm:ss.uuuuuu 时间戳?
【发布时间】:2020-11-10 19:06:44
【问题描述】:

我希望在 C++ 中打印 hh:mm:ss.uuuuuu 时间戳。看来我需要使用 chrono 库和std::chrono::use high_resolution_clock::now()?

我不确定如何从这里开始。

【问题讨论】:

  • uuuuuu 毫秒是多少?微秒?
  • @JonnyHenly u 在时间格式中通常表示微秒。此外,微秒意味着 6 位精度,与指定的 uuuuuu 匹配。

标签: c++ time chrono


【解决方案1】:

使用与 C++11/14/17 配合使用的 C++20 chrono preview library 可以轻松实现这一点:

#include "date/date.h"
#include <chrono>
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std;
    using namespace std::chrono;
    cout << format("%T", floor<microseconds>(system_clock::now())) << '\n';
}

只为我输出:

19:31:54.033196

这将通过以下方式移植到 C++20:

  • 删除#include "date/date.h"
  • 删除using namespace date;
  • 将"%T" 更改为"{:%T}"

这是一个只有头文件的开源库。

输出为 UTC。如果您需要本地时间,也可以使用,但该库不是仅限标题的。它在同一个链接中,可以这样使用:

#include "date/tz.h"
#include <chrono>
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std;
    using namespace std::chrono;
    zoned_time zt{current_zone(), floor<microseconds>(system_clock::now()))};
    cout << format("%T", zt) << '\n';
}

以上语法使用 C++17。如果您使用 C++11 或 14,请将 zoned_time 更改为 zoned_time&lt;microseconds&gt;。

Some installation is required for the tz.h library.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2012-04-03
    • 2019-06-05
    相关资源
    最近更新 更多