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

2022-01-13 00:00:00 timestamp c++

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

In Java, we can use System.currentTimeMillis() to get the current timestamp in Milliseconds since epoch time which is -

当前时间和当前时间之间的差异,以毫秒为单位UTC 时间 1970 年 1 月 1 日午夜.

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

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

In C++ how to get the same thing?

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

Currently I am using this to get the current timestamp -

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 纪元以来的毫秒数,如下所示:

If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:

#include <chrono>

// ...

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

相关文章