c++ double时间戳转年月日时分秒毫秒格式, 再转换成字符串打印
时间: 2025-01-30 10:10:46 浏览: 79
在C++中,你可以使用`<chrono>`库来处理时间和日期。首先,你需要将double类型的Unix时间戳(自1970年1月1日以来的秒数)转换为`std::chrono::time_point`或`std::chrono::system_clock::time_point`。然后,你可以提取出年、月、日、时、分、秒和毫秒,并将它们组合成所需的格式。
以下是一个示例:
```cpp
#include <iostream>
#include <sstream>
#include <chrono>
// 时间戳到时间点
std::chrono::system_clock::time_point fromDouble(double timestamp) {
return std::chrono::system_clock::from_time_t(std::chrono::seconds(timestamp));
}
// 将时间点转换为指定格式的字符串
std::string timePointToDateString(const std::chrono::system_clock::time_point& tp) {
using namespace std::chrono;
auto now = tp;
auto local_day = system_clock::to_local(now);
auto t = local_day.time_since_epoch();
// 分割并格式化
auto year = now.year();
auto month = now.month_name();
auto day = now.day_of_month();
auto hour = std::put_time(std::localtime(&t), "%H");
auto minute = std::put_time(std::localtime(&t), "%M");
auto second = std::put_time(std::localtime(&t), "%S");
auto millisecond = std::put_time(std::localtime(&t), ".%f").substr(0, 3); // 获取前三位毫秒
std::ostringstream oss;
oss << year << "年" << month << "月" << day << "日 " << hour << ":" << minute << ":" << second << "." << millisecond;
return oss.str();
}
int main() {
double timestamp = your_timestamp_value; // 替换为实际的时间戳值
std::string formatted_date = timePointToDateString(fromDouble(timestamp));
std::cout << formatted_date << std::endl;
阅读全文
相关推荐















