gpt4 book ai didi

c++ - 如何像 Java 一样获取自 1970 年以来的当前时间戳(以毫秒为单位)

转载 作者:IT老高 更新时间:2023-10-28 11:52:38 25 4
gpt4 key购买 nike

在 Java 中,我们可以使用 System.currentTimeMillis() 来获取自纪元时间以来的当前时间戳(以毫秒为单位),即 -

the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

在 C++ 中如何得到相同的东西?

目前我正在使用它来获取当前时间戳 -

struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds

cout << ms << endl;

这看起来对吗?

最佳答案

如果您有权访问 C++ 11 库,请查看 std::chrono图书馆。您可以使用它来获取自 Unix 纪元以来的毫秒数,如下所示:

#include <chrono>

// ...

using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
);

关于c++ - 如何像 Java 一样获取自 1970 年以来的当前时间戳(以毫秒为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19555121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com