我需要在 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/