C++如何获得当前时间
时间: 2024-05-03 09:02:14 浏览: 12
在C语言中,可以使用time.h库中的time()函数来获取当前时间。该函数返回自1970年1月1日以来经过的秒数。可以使用localtime()函数将返回的秒数转换为本地时间。以下是一个示例代码:
```
#include <stdio.h>
#include <time.h>
int main() {
time_t current_time;
struct tm * time_info;
char time_string[50];
time(¤t_time);
time_info = localtime(¤t_time);
strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info);
printf("Current time is: %s\n", time_string);
return 0;
}
```
其中,time()函数获取当前时间,localtime()函数将时间转换为本地时间,并使用strftime()函数将时间格式化成字符串。
相关问题
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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)