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

问题描述 投票:0回答:5

在 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++ timestamp
5个回答
353
投票

如果您有权访问 C++ 11 库,请查看

std::chrono
库。您可以使用它来获取自 Unix 纪元以来的毫秒数,如下所示:

#include <chrono>

// ...

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

57
投票

从 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;
}

49
投票

使用

<sys/time.h>

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

参考这个


32
投票

这个答案与 Oz.'s 非常相似,在 C++ 中使用

<chrono>
——我没有从 Oz 那里得到它。虽然...

我在本页底部找到了原始片段,并对其进行了稍微修改,使其成为一个完整的控制台应用程序。我喜欢用这个小东西。如果您需要编写大量脚本,并且需要 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;
}

14
投票

如果使用 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.