std::tm转std::string
时间: 2023-11-17 16:05:59 浏览: 44
可以使用std::put_time函数将std::tm类型的时间转换为std::string类型。具体实现方法如下:
```
#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>
int main() {
std::tm info = {0};
info.tm_year = 121; // 年份为2021
info.tm_mon = 6; // 月份为7月
info.tm_mday = 1; // 日为1日
info.tm_hour = 12; // 小时为12时
info.tm_min = 30; // 分钟为30分
info.tm_sec = 0; // 秒为0秒
std::stringstream ss;
ss << std::put_time(&info, "%Y-%m-%d %H:%M:%S");
std::string str = ss.str();
std::cout << str << std::endl;
return 0;
}
```
上述代码中,我们首先定义了一个std::tm类型的时间info,然后使用std::put_time函数将其转换为std::string类型的时间,并将其存储在std::stringstream类型的ss中,最后通过ss.str()函数将其转换为std::string类型并输出。其中,%Y表示年份,%m表示月份,%d表示日,%H表示小时,%M表示分钟,%S表示秒。你可以根据自己的需要修改输出格式。