C加加把获取的日期变成字符串
时间: 2024-10-10 11:06:10 浏览: 35
在C++中,你可以使用标准库中的<chrono>和<string>头文件来将日期转换成字符串。以下是一个简单的示例,展示如何使用`std::chrono::system_clock`获取当前时间并格式化为字符串:
```cpp
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
int main() {
// 获取当前系统时间
auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
// 将time_t转换为struct tm以便格式化
std::tm time_info {};
localtime_s(&time_info, &now);
// 创建一个strftime格式化字符串
char formatted_date[80];
std::strftime(formatted_date, sizeof(formatted_date), "%Y-%m-%d %H:%M:%S", &time_info);
// 输出日期字符串
std::cout << "Current date and time: " << formatted_date << std::endl;
return 0;
}
```
在这个例子中,`%Y-%m-%d %H:%M:%S`是一个格式说明符,用于指定日期时间的输出样式,分别是年月日、小时分钟秒。
阅读全文
相关推荐


















