C++将时间戳转换为年月日时分秒格式
时间: 2023-09-07 10:17:28 浏览: 394
可以使用C++11中的`std::chrono`库来实现时间戳到年月日时分秒的转换。
以下是一个示例代码:
```c++
#include <iostream>
#include <chrono>
#include <ctime>
#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();
// 转换为本地时间
std::time_t current_time = static_cast<std::time_t>(timestamp);
std::tm* time_info = std::localtime(¤t_time);
// 输出年月日时分秒
std::cout << "Year: " << time_info->tm_year + 1900 << std::endl;
std::cout << "Month: " << time_info->tm_mon + 1 << std::endl;
std::cout << "Day: " << time_info->tm_mday << std::endl;
std::cout << "Hour: " << time_info->tm_hour << std::endl;
std::cout << "Minute: " << time_info->tm_min << std::endl;
std::cout << "Second: " << time_info->tm_sec << std::endl;
return 0;
}
```
输出结果为:
```
Year: 2021
Month: 11
Day: 12
Hour: 14
Minute: 30
Second: 45
```
可以看到,将时间戳转换为年月日时分秒格式非常简单,只需要使用`std::chrono`库和`std::localtime`函数即可。
阅读全文