讲时间戳转换成yy-mm-dd hh-mm-ss格式得C++代码
时间: 2023-10-04 18:08:51 浏览: 71
以下是将时间戳转换为 yy-mm-dd hh-mm-ss 格式的 C++ 代码:
```c++
#include <iostream>
#include <ctime>
#include <chrono>
#include <iomanip>
int main() {
// 获取当前时间戳
auto now = std::chrono::system_clock::now().time_since_epoch();
auto timestamp = std::chrono::duration_cast<std::chrono::seconds>(now).count();
// 将时间戳转换为 struct tm 类型
std::time_t t = static_cast<std::time_t>(timestamp);
std::tm* timeinfo = std::localtime(&t);
// 输出时间字符串
std::cout << std::put_time(timeinfo, "%y-%m-%d %H:%M:%S") << std::endl;
return 0;
}
```
代码中使用了 C++11 中的 `<chrono>` 和 `<iomanip>` 库,其中:
- `std::chrono::system_clock::now()` 获取当前时间;
- `std::chrono::duration_cast<std::chrono::seconds>(now).count()` 将时间转换为秒级时间戳;
- `std::localtime(&t)` 将时间戳转换为本地时间;
- `std::put_time(timeinfo, "%y-%m-%d %H:%M:%S")` 将 `struct tm` 类型的时间格式化为字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)