C++年月日时分秒与时间戳互相转换
时间: 2024-12-31 20:20:25 浏览: 319
### C++ 中日期时间和时间戳之间的相互转换
在 C++ 中,可以利用 `<chrono>` 库来实现日期时间和时间戳之间的转换。下面分别介绍两种方向的转换方法。
#### 将日期时间转换为时间戳
为了将具体的日期时间(年、月、日、时、分、秒)转换成 Unix 时间戳,在现代 C++ (C++11 及以上版本) 中可以通过 `std::chrono` 来完成此操作:
```cpp
#include <iostream>
#include <chrono>
int main() {
using namespace std::chrono;
// 定义具体的时间点
auto tp = sys_days{January/1, 2023} + hours(8);
// 转换为自纪元以来的秒数表示形式即Unix时间戳
auto epoch_time = time_point_cast<seconds>(tp).time_since_epoch().count();
std::cout << "Timestamp: " << epoch_time << '\n';
}
```
上述代码片段展示了如何创建特定的日期时间并将其转为基于秒的时间戳[^1]。
#### 将时间戳转换回日期时间
对于从时间戳恢复到可读性的日期时间格式,则同样依赖于 `std::chrono` 提供的功能来进行逆向处理:
```cpp
#include <iostream>
#include <iomanip>
#include <sstream>
#include <chrono>
int main(){
using namespace std::chrono;
// 假设有一个给定的时间戳
int64_t timestamp = 1704086400; // 对应的是2024-01-01T00:00:00Z
system_clock::time_point tp(seconds(timestamp));
// 使用put_time函数打印出本地时间字符串
auto local_tm = current_zone()->to_local(tp);
std::stringstream ss;
ss << std::put_time(&local_tm, "%Y-%m-%d %H:%M:%S");
std::string formattedTime = ss.str();
std::cout << "Formatted Date Time: " << formattedTime << "\n";
}
```
这段程序说明了怎样把整型变量存储的时间戳解析成为人类易于理解的标准日期时间格式。
阅读全文
相关推荐















