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

How to get current timestamp in milliseconds since 1970 just the way Java gets

本文关键字:时间戳 就像 一样 Java 为单位 获取 1970      更新时间:2023-10-16

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

当前

时间和当前时间之间的差异(以毫秒为单位) 世界协调时 1970 年 1 月 1 日午夜。

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++11 开始,您可以使用std::chrono

  • 获取当前系统时间:std::chrono::system_clock::now()
  • 获取自纪元以来的时间:.time_since_epoch()
  • 将基础单位转换为毫秒:duration_cast<milliseconds>(d)
  • std::chrono::milliseconds转换为整数(uint64_t以避免溢出)
#include <chrono>
#include <cstdint>
#include <iostream>
uint64_t timeSinceEpochMillisec() {
  using namespace std::chrono;
  return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
int main() {
  std::cout << timeSinceEpochMillisec() << std::endl;
  return 0;
}

使用<sys/time.h>

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

参考这个。

这个答案与奥兹的非常相似,使用<chrono>表示C++——我不是从奥兹那里抢来的。

我在此页面底部选择了原始代码段,并对其进行了轻微修改,使其成为一个完整的控制台应用程序。我喜欢使用这个 lil' ol' 的东西。如果您执行大量脚本编写,并且需要在Windows中使用可靠的工具来在实际毫秒内获得纪元,而无需使用VB或一些不太现代,不太适合阅读的代码,那就太棒了。

#include <chrono>
#include <iostream>
int main() {
    unsigned __int64 now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
    std::cout << now << std::endl;
    return 0;
}
如果使用

gettimeofday,则必须转换为long long,否则您将获得溢出,因此不是自纪元以来的实际毫秒数: Long int msint = tp.tv_sec * 1000 + tp.tv_usec/1000;会给你一个数字,比如767990892,它是纪元后 8 天左右的 ;-)。

int main(int argc, char* argv[])
{
    struct timeval tp;
    gettimeofday(&tp, NULL);
    long long mslong = (long long) tp.tv_sec * 1000L + tp.tv_usec / 1000; //get current timestamp in milliseconds
    std::cout << mslong << std::endl;
}