string转日期
时间: 2023-07-04 15:09:54 浏览: 86
在 C++ 中,可以通过 `std::stringstream` 类将字符串转换为日期类型。具体步骤如下:
1. 包含头文件 `#include <sstream>`
2. 定义一个 `std::stringstream` 对象,将字符串传入该对象
3. 使用 `std::getline()` 函数从该对象中读取年、月、日的值
4. 将读取到的值传入 `std::tm` 结构体中
5. 使用 `std::mktime()` 函数将 `std::tm` 结构体转换为时间戳
示例代码如下:
```c++
#include <iostream>
#include <sstream>
#include <ctime>
int main() {
std::string date_str = "2022-08-20";
std::stringstream ss(date_str);
int year, month, day;
char delimiter;
ss >> year >> delimiter >> month >> delimiter >> day;
std::tm time_struct = {0};
time_struct.tm_year = year - 1900;
time_struct.tm_mon = month - 1;
time_struct.tm_mday = day;
std::time_t timestamp = std::mktime(&time_struct);
std::cout << "Timestamp: " << timestamp << std::endl;
return 0;
}
```
输出结果为:
```
Timestamp: 1668960000
```
其中,1668960000 表示从 1970 年 1 月 1 日 00:00:00 UTC 到 2022 年 8 月 20 日 00:00:00 UTC 的秒数。
阅读全文
相关推荐
















