如何像 Java 一样获取自 1970 年以来的当前时间戳(以毫秒为单位) [英] How to get current timestamp in milliseconds since 1970 just the way Java gets

查看:52
本文介绍了如何像 Java 一样获取自 1970 年以来的当前时间戳(以毫秒为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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()
);

这篇关于如何像 Java 一样获取自 1970 年以来的当前时间戳(以毫秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆