C++ 获取系统时间
时间: 2023-07-16 19:13:26 浏览: 98
C++ 中获取系统时间可以使用 `<ctime>` 头文件中的 `time()` 函数。该函数返回从 1970 年 1 月 1 日 00:00:00 UTC 到当前时间的秒数。
以下是一个简单的示例代码:
```c++
#include <iostream>
#include <ctime>
int main() {
// 获取当前时间
std::time_t now = std::time(nullptr);
// 转换为本地时间
std::tm local_time = *std::localtime(&now);
// 输出时间
std::cout << "当前时间为:"
<< local_time.tm_year + 1900 << "-"
<< local_time.tm_mon + 1 << "-"
<< local_time.tm_mday << " "
<< local_time.tm_hour << ":"
<< local_time.tm_min << ":"
<< local_time.tm_sec << std::endl;
return 0;
}
```
在上面的示例代码中,我们使用了 `time()` 函数获取当前时间,然后使用 `localtime()` 函数将其转换为本地时间,最后输出时间。
相关问题
c++获取当前时间
可以使用C++中的ctime库来获取当前时间,具体实现可以使用以下代码:
```cpp
#include <ctime>
#include <iostream>
int main() {
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result)) << std::endl;
return 0;
}
```
其中,`std::time(nullptr)`会返回当前的时间戳,`std::localtime`函数会将时间戳转换为当地时间,并返回一个tm结构体,再使用`std::asctime`函数将tm结构体转换为字符串格式的时间。
c++ 获取系统时间
C++ 中获取系统时间可以使用 `<ctime>` 头文件中的 `time()` 函数。该函数返回从 1970 年 1 月 1 日 00:00:00 UTC 到当前时间的秒数。
以下是一个简单的示例代码:
```c++
#include <iostream>
#include <ctime>
int main() {
// 获取当前时间
std::time_t now = std::time(nullptr);
// 转换为本地时间
std::tm local_time = *std::localtime(&now);
// 输出时间
std::cout << "当前时间为:"
<< local_time.tm_year + 1900 << "-"
<< local_time.tm_mon + 1 << "-"
<< local_time.tm_mday << " "
<< local_time.tm_hour << ":"
<< local_time.tm_min << ":"
<< local_time.tm_sec << std::endl;
return 0;
}
```
在上面的示例代码中,我们使用了 `time()` 函数获取当前时间,然后使用 `localtime()` 函数将其转换为本地时间,最后输出时间。
阅读全文
相关推荐















