
用 C++ 将时间戳(如 time_t 类型的秒级或毫秒级整数)转成格式化日期字符串,核心是借助标准库中的 std::tm 和 std::strftime,或 C++20 的 与 (需编译器支持)。下面分场景给出清晰、可直接运行的代码示例。
✅ 秒级时间戳 → “yyYY-MM-DD HH:MM:SS”(兼容 C++11 及以上)
这是最常用场景。注意:localtime_r(linux/macOS)或 localtime_s(windows)更安全,避免静态缓冲区竞争;若仅单线程且不介意,可用 localtime。
#include #include #include std::string timestampToFormattedString(time_t ts) { struct tm tm_info; #ifdef _WIN32 localtime_s(&tm_info, &ts); // windows 安全版本 #else localtime_r(&ts, &tm_info); // POSIX 安全版本 #endif char buf[64]; strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm_info); return std::string(buf); } int main() { time_t now = std::time(nullptr); std::cout << timestampToFormattedString(now) << "n"; // 示例输出:2024-05-22 14:38:21 }
✅ 毫秒级时间戳(如 1684762701123)→ 带毫秒的字符串
毫秒时间戳需先转为秒 + 毫秒余数,再用 std::tm 解析秒部分,手动拼接毫秒。
#include #include #include #include std::string msTimestampToFormattedString(long long ms_ts) { time_t sec = ms_ts / 1000; int ms = ms_ts % 1000; struct tm tm_info; #ifdef _WIN32 localtime_s(&tm_info, &sec); #else localtime_r(&sec, &tm_info); #endif char buf[64]; strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm_info); std::ostringstream oss; oss << buf << '.' << std::setfill('0') << std::setw(3) << ms; return oss.str(); } // 使用前加:#include
✅ C++20 方式:用 + (简洁现代,需 /std:c++20 或 -std=c++20)
无需手动处理 tm,类型安全,支持时区(需额外库如 date.h),默认本地时区。
立即学习“C++免费学习笔记(深入)”;
#include #include #include #include std::string timestampToFormattedCpp20(std::chrono::system_clock::time_point tp) { return std::format("{:%Y-%m-%d %H:%M:%S}", tp); } // 用法示例(秒级时间戳): auto ts_sec = static_cast(1716417501); auto tp = std::chrono::system_clock::from_time_t(ts_sec); std::cout << timestampToFormattedCpp20(tp) << "n";
⚠️ 注意:std::format 在 GCC 13+ / Clang 15+ / MSVC 2022 17.5+ 中已较稳定,但早期版本可能需启用实验性支持或使用第三方 fmt 库替代。
? 小贴士:时区与 UTC
上面示例默认转成本地时区。如需 UTC 时间,把 localtime_* 换成 gmtime_*,或 C++20 中用 std::format("{:%Y-%m-%d %H:%M:%S}Z", std::chrono::utc_clock::from_sys(tp))(需 C++20 时区支持)。
常见格式符参考:%Y(4位年)、%m(月)、%d(日)、%H(24小时)、%M(分)、%S(秒)、%F(等价于 %Y-%m-%d)、%T(等价于 %H:%M:%S)。