c++ - 将当前日期精确到毫秒

标签 c++ c++11 c++-chrono

我需要在 c++11 中以可打印格式获取当前 UTC 日期,精确到毫秒。我需要它在 Windows 和 Linux 上运行,因此首选跨平台代码。如果这是不可能的,我可以编写两个单独的实现。

这是我尝试过的:

std::chrono::time_point<std::chrono::high_resolution_clock> time = std::chrono::system_clock::now();
std::time_t tt = std::chrono::high_resolution_clock::to_time_t(time);

struct tm* utc = nullptr;
gmtime_s(utc, &tt);

char buffer[256];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%dT-%H:%M:%S. %MILLESECONDS???, utc);

尽管如您所见,这并没有将其精确到毫秒。如果需要的话,只要我能以某种方式获得毫秒值,我就可以自己格式化字符串。

最佳答案

time_t 仅包含秒,因此您可以使用 std::chrono 函数来获得更高的精度:

#include <iostream>
#include <chrono>

int main() 
{
    typedef std::chrono::system_clock clock_type;

    auto now = clock_type::now();
    auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
    auto fraction = now - seconds;
    time_t cnow = clock_type::to_time_t(now);

    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(fraction);
    std::cout << "Milliseconds: " << milliseconds.count() << '\n';
}

关于c++ - 将当前日期精确到毫秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40090488/

相关文章:

c++ - 在变量返回之前存储值

android - NDK c++ std::thread 在加入时中止崩溃

c++ - 填充结构 tm

c++ - 带按值参数 & noexcept 的构造函数

templates - 使用 boost::graph 实现异构节点类型和边类型

c++ - std::chrono::duration_cast 1 秒和 2 秒的奇怪结果

c++ - 如何将分数纪元时间戳( double )转换为 std::chrono::time_point?

c++ - 运算符重载 C++ 引用或值

c++ - Boost::thread 如何在主线程和工作线程之间同步?

c++ - 模拟条件 back_inserter 之类的最佳方法?