C++如何获取当前时间
时间: 2024-06-14 18:06:24 浏览: 8
以下是两种获取当前时间的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);
}
```
相关问题
c++ 获取当前时间
以下是两种C++获取当前时间的例子:
1.使用GetTickCount()函数获取当前时间,可精确到毫秒:
```cpp
#include <windows.h>
#include <iostream>
using namespace std;
int main(int argc, _TCHAR* argv[]) {
DWORD time_start, time_end;
/* 获取开始时间 */
time_start = GetTickCount(); //从操作系统启动经过的毫秒数
Sleep(3000);
time_end = GetTickCount();
cout << "Time = " << (time_end - time_start) << "ms\n ";
return 0;
}
```
2.使用GetLocalTime()函数获取当前时间,可精确到秒:
```cpp
#include <windows.h>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
SYSTEMTIME st = { 0 };
GetLocalTime(&st); //获取当前时间 可精确到ms
printf("%d-%02d-%02d %02d:%02d:%02d\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return 0;
}
```
C++ 获取当前时间
获取当前时间可以使用C语言的time.h头文件中的time函数。下面是一个示例代码:
```c
#include <stdio.h>
#include <time.h>
int main() {
time_t currentTime;
struct tm *localTime;
// 获取当前时间
currentTime = time(NULL);
localTime = localtime(¤tTime);
// 输出当前时间
printf("当前时间为:%02d:%02d:%02d\n",
localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
return 0;
}
```
运行以上代码会输出当前的小时、分钟和秒数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)