C++中如何获取当前时间?
时间: 2024-06-14 18:06:57 浏览: 21
以下是两种在C++中获取当前时间的方法:
1. 使用std::time()函数获取当前时间戳:
```cpp
#include <iostream>
#include <ctime>
int main() {
std::time_t now = std::time(nullptr);
std::cout << "Current timestamp: " << now << std::endl;
return 0;
}
```
2. 使用std::chrono::system_clock::now()函数获取当前时间戳:
```cpp
#include <iostream>
#include <chrono>
int main() {
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
std::cout << "Current timestamp: " << timestamp << std::endl; return 0;
}
```
相关问题
C++中获取当前时间
以下是两种在C++中获取当前时间的方法:
1. 使用ctime库函数获取当前时间:
```cpp
#include <iostream>
#include <ctime>
int main() {
// 获取当前时间
time_t now = time(0);
// 将时间转换为字符串格式
char* timeStr = ctime(&now);
// 输出当前时间
std::cout << "Current time is: " << timeStr << std::endl;
return 0;
}
```
2. 使用chrono库获取当前时间:
```cpp
#include <iostream>
#include <chrono>
int main() {
// 获取当前时间点
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
// 将时间点转换为时间结构体
std::time_t time = std::chrono::system_clock::to_time_t(now);
// 将时间转换为字符串格式
char* timeStr = std::ctime(&time);
// 输出当前时间
std::cout << "Current time is: " << timeStr << std::endl;
return 0;
}
```
C++如何获取当前时间
以下是两种获取当前时间的C++代码示例:
1. 使用CTime类获取当前时间:
```cpp
#include <atltime.h>
#include <stdio.h>
int main() {
CTime time = CTime::GetCurrentTime();
printf("%04d/%02d/%02d %02d:%02d:%02d\n", time.GetYear(), time.GetMonth(), time.GetDay(), time.GetHour(), time.GetMinute(), time.GetSecond());}
```
2. 使用time函数和tm结构体获取当前时间:
```cpp
#include <ctime>
#include <stdio.h>
int main() {
time_t nowtime;
time(&nowtime); // 获取1970年1月1日0点0分0秒到现在经过的秒数
tm p;
localtime_s(&p, &nowtime); // 将秒数转换为本地时间,年从1900算起,需要+1900,月为0-11,所以要+1
printf("%04d:%02d:%02d %02d:%02d:%02d\n", p.tm_year + 1900, p.tm_mon + 1, p.tm_mday, p.tm_hour, p.tm_min, p.tm_sec);
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)