chrono 使用put_time转化为字符串后还可以转化为system_clock对象吗
时间: 2024-10-17 09:11:34 浏览: 38
`std::chrono::put_time`函数通常用于格式化`std::chrono`的时间点到`std::string`,以便于人类阅读。这个函数本身并不能直接将格式化的字符串转换回`system_clock`的对象。你需要先解析字符串并重新构造时间点。
如果你有一个已经格式化的字符串,你可以使用`std::istringstream`或者其他日期/时间解析库(如C++20引入的`std::chrono::parse`),尝试将其转换回`system_clock::duration`或`system_clock::time_point`。示例如下:
```cpp
#include <iostream>
#include <sstream>
#include <chrono>
std::chrono::system_clock::time_point parse_time_string(const std::string& str) {
std::istringstream iss(str);
std::chrono::time_point<std::chrono::system_clock> tp;
if (!(iss >> std::chrono::system_clock::from_time_t(tp.time_since_epoch()))) {
throw std::runtime_error("Invalid time string");
}
return tp;
}
int main() {
std::string formatted_time = "2023-06-01T12:00:00Z";
try {
std::chrono::system_clock::time_point parsed_tp = parse_time_string(formatted_time);
// 接下来你可以使用parsed_tp进行操作...
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << '\n';
}
return 0;
}
```
在这个例子中,`parse_time_string`函数试图从给定的字符串中提取`system_clock::time_point`。如果解析失败,会抛出异常。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![](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)