How to get current timestamp in milliseconds since 1970 just the way Java gets(如何像 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 年以来的当前时间戳(以毫秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何像 Java 一样获取自 1970 年以来的当前时间戳(以毫秒为单位)


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01