cpp如何获取系统时间
时间: 2024-05-09 22:17:41 浏览: 7
要获取系统时间,可以使用time.h头文件中的time()函数。代码示例如下:
```cpp
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t now = time(0); // 获取当前系统时间
char* dt = ctime(&now); // 将时间转换为字符串
cout << "当前时间为: " << dt << endl;
return 0;
}
```
输出:
```
当前时间为: Sun Sep 19 13:23:27 2021
```
相关问题
cpp获取当前时间
在 C++ 中,可以使用 `<ctime>` 头文件中的函数来获取当前时间。以下是一个示例代码:
```cpp
#include <iostream>
#include <ctime>
int main() {
// 获取当前时间
std::time_t current_time = std::time(nullptr);
// 将时间转换为本地时间
std::tm* local_time = std::localtime(¤t_time);
// 输出本地时间
std::cout << "Current time: "
<< 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;
}
```
输出结果类似于:
```
Current time: 2022-2-14 14:30:0
```
Qt cpp 获取当前时间,并将星期用中文表示
可以使用 Qt 的 QDate 类和 QLocale 类来实现获取当前时间并将星期用中文表示的功能。
示例代码如下:
```cpp
#include <QDate>
#include <QLocale>
#include <QDebug>
int main()
{
QDate currentDate = QDate::currentDate();
QString weekDay = QLocale::system().dayName(currentDate.dayOfWeek(), QLocale::ShortFormat);
qDebug() << "当前时间为:" << currentDate.toString("yyyy年MM月dd日") << weekDay;
return 0;
}
```
上述代码中,首先使用 `QDate::currentDate()` 获取当前日期,并存储在 `currentDate` 变量中。然后使用 `QLocale::system().dayName()` 获取当前日期的星期名称,该函数会根据当前系统的语言环境返回相应的星期名称,其中 `QLocale::ShortFormat` 表示返回短格式的星期名称。最后使用 `QString::toString()` 将日期格式化为中文格式,并与星期名称一起输出到控制台。
执行上述代码,将会输出当前时间及星期的中文表示,例如:
```
当前时间为:2022年07月13日 周三
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)