c++获取当前时间戳,单位是毫秒
时间: 2024-03-30 07:10:52 浏览: 161
你可以使用 `time.h` 中的 `time()` 函数来获取当前的时间戳,它的返回值是从 1970 年 1 月 1 日 00:00:00 UTC 到现在的时间(以秒为单位)。如果你需要以毫秒为单位的时间戳,你可以使用 `time()` 函数的返回值除以 1000。
下面是一个使用 `time()` 函数获取当前时间戳的例子:
```c
#include <stdio.h>
#include <time.h>
int main() {
time_t t = time(NULL);
printf("当前时间戳(秒):%ld\n", t);
printf("当前时间戳(毫秒):%ld\n", t * 1000);
return 0;
}
```
输出结果类似这样:
```
当前时间戳(秒):1610417016
当前时间戳(毫秒):1610417016000
```
相关问题
C++ 获取当前时间戳 精确到毫秒
可以使用C++11中的chrono库来获取当前时间戳,然后再将其转换为精确到毫秒的时间戳。
以下是示例代码:
```cpp
#include <chrono>
#include <iostream>
int main() {
// 获取当前时间戳
auto now = std::chrono::system_clock::now();
// 转换为精确到毫秒的时间戳
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
auto value = now_ms.time_since_epoch().count();
// 输出时间戳
std::cout << "当前时间戳(毫秒): " << value << std::endl;
return 0;
}
```
运行结果类似于:
```
当前时间戳(毫秒): 1640427490455
```
其中,`std::chrono::system_clock::now()`获取当前时间戳,`std::chrono::time_point_cast<std::chrono::milliseconds>(now)`将时间戳转换为精确到毫秒的时间戳,`now_ms.time_since_epoch().count()`获取时间戳的数值。
C++ 获取当前时间戳 精确到毫秒 不使用chrono库
如果你不想使用C++11的chrono库,也可以使用C++标准库中的ctime库来获取当前时间戳,然后再将其转换为精确到毫秒的时间戳。
以下是示例代码:
```cpp
#include <ctime>
#include <iostream>
int main() {
// 获取当前时间
std::time_t now = std::time(nullptr);
// 转换为精确到毫秒的时间戳
long long int value = now * 1000LL;
// 输出时间戳
std::cout << "当前时间戳(毫秒): " << value << std::endl;
return 0;
}
```
运行结果类似于:
```
当前时间戳(毫秒): 1640427490455
```
其中,`std::time(nullptr)`获取当前时间戳,`now * 1000LL`将时间戳转换为精确到毫秒的时间戳。需要注意的是,这种方法得到的时间戳是以1970年1月1日 00:00:00为起点的。
阅读全文
相关推荐
















