如何以毫秒为单位获取自 1970 年以来的当前时间戳,就像 Java 一样
How to get current timestamp in milliseconds since 1970 just the way Java gets
在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;
}
相关文章:
- C++:floor unix时间戳到UTC月份
- 如何在c++中录制具有精确帧时间戳的视频
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- Google protobuf 时间戳未声明标识符,在 Windows 上具有C++
- 在多个时间戳处执行函数
- 以天C++为单位的两个时间戳之间的差异
- 获取 QInputEvent 在 Qt 4.8 中被放入 QEventLoop 队列时的时间戳
- 在 C++ 中为文件名添加时间戳
- 如何从远程 SFTP 服务器获取 HH-MM-SS 时间戳格式的文件列表
- 如何将消息时间戳写入日志文件?
- 我们可以将集合的值存储在变量中吗?就像我们可以将数组的值存储在变量中一样
- 将时间戳打印到流的最简单方法
- 如何使用 redis-plus-plus 存储二进制数据,就像我想存储结构一样?@for_stack?
- 如何将到达图形视图右侧(末端)的QGraphicsPixmapItem移动到左侧(开始)侧(就像在贪吃蛇游戏中发生的事情
- 读取悖论时间戳字段
- 为什么C++中没有常量引用,就像常量指针一样?
- C++程序中多个位置的时间 (0) 时间戳
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 在 c++ 中获取 X 毫秒前的时间戳
- 如何以毫秒为单位获取自 1970 年以来的当前时间戳,就像 Java 一样