使用 localtime 和 strftime 可将时间戳转为格式化日期字符串,如 "%Y-%m-%d %H:%M:%S" 对应 2025-04-05 14:30:00;需注意 localtime 非线程安全,多线程应使用 localtime_s 或 localtime_r;UTC 时间可用 gmtime。

在C++中将时间戳转换为日期字符串,通常使用标准库中的 ctime 头文件提供的函数。最常用的方法是结合 localtime 或 gmtime 与 strftime 函数进行格式化输出。
将时间戳(如 time_t 类型)转换为本地时间,并按指定格式输出为字符串。
示例代码:
#include <iostream>
#include <ctime>
#include <string>
<p>std::string formatTimestamp(time_t timestamp) {
char buffer[80];
std::tm* timeinfo = std::localtime(×tamp);
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
return std::string(buffer);
}</p><p>int main() {
time_t now = std::time(nullptr); // 当前时间戳
std::string formatted = formatTimestamp(now);
std::cout << "当前时间: " << formatted << std::endl;
return 0;
}</p>strftime 支持多种格式控制符,常见如下:
立即学习“C++免费学习笔记(深入)”;
你可以组合这些符号来定义输出格式,比如:
"%Y年%m月%d日 %H:%M"
会输出类似:
2025年04月05日 14:30
std::localtime 返回的是静态缓冲区指针,不是线程安全的。在多线程环境下建议使用其可重入版本:
跨平台处理建议封装判断:
#ifdef _WIN32
std::tm timeinfo;
localtime_s(&timeinfo, ×tamp);
#else
std::tm timeinfo;
localtime_r(×tamp, &timeinfo);
#endif
若需UTC时间,使用 std::gmtime 替代 localtime。
基本上就这些。掌握 strftime 的格式化方式,就能灵活输出任意需要的时间字符串。
以上就是c++++如何将时间戳转换为日期字符串_C++时间格式化输出方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号