C++如何获取当前时间
时间: 2024-06-14 20:06:24 浏览: 173
以下是两种获取当前时间的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);
}
```
阅读全文
相关推荐
















