C++中格式化时间输出常用strftime和std::put_time:前者为C风格函数,需缓冲区与格式化字符串,适用于简单场景;后者是C++11流操作符,结合ostringstream使用,更安全且支持本地化,如中文时间显示需设置locale。两者均支持%Y、%m、%d等格式符,按项目需求选择。

在C++中格式化时间输出,常用的方法有C风格的strftime函数和C++11引入的流操作符std::put_time。两者都能将时间结构转换为指定格式的字符串,适用于日志记录、界面显示等场景。
strftime 函数使用方法
strftime 是定义在
函数原型如下:
size_t strftime(char* str, size_t maxsize, const char* format, const struct tm* timeptr);参数说明:
立即学习“C++免费学习笔记(深入)”;
- str:输出字符串缓冲区
- maxsize:缓冲区最大长度
- format:格式化字符串(类似 printf)
- timeptr:指向 tm 结构的时间数据
示例代码:
#include iostream>#include
int main() {
std::time_t t = std::time(nullptr);
std::tm* local_tm = std::localtime(&t);
char buffer[100];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_tm);
std::cout return 0;
}
输出结果类似:
当前时间: 2024-04-05 14:30:22put_time 使用实例
std::put_time 是C++11提供的流操作符,配合 使用,更符合C++风格。
需要包含头文件 stream> 来构建字符串。
示例代码:
#include#include
#include
#include
int main() {
std::time_t t = std::time(nullptr);
std::tm* local_tm = std::localtime(&t);
std::ostringstream oss;
oss
std::cout return 0;
}
输出结果:
2024年04月05日 14时30分22秒注意:std::put_time 依赖本地环境的locale设置。若输出乱码或英文月份,可尝试设置locale:
std::locale::global(std::locale("zh_CN.UTF-8"));常用格式化符号对照表
两种方法支持相同的格式占位符:
- %Y:四位年份,如 2024
- %y:两位年份,如 24
- %m:月份(01–12)
- %d:日期(01–31)
- %H:小时(24小时制,00–23)
- %I:小时(12小时制,01–12)
- %M:分钟(00–59)
- %S:秒(00–60,支持闰秒)
- %F:等价于 %Y-%m-%d
- %T:等价于 %H:%M:%S
- %c:本地化时间表示
基本上就这些。根据项目风格选择合适的方式,C风格简单直接,C++方式更灵活安全。










