将当前日期精确到毫秒

Get current date down to milliseconds

本文关键字:当前日期      更新时间:2023-10-16

我需要以可打印格式获得当前UTC日期,在c++11中精确到毫秒。我需要这个在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';
}