在C++开发中,时间格式化是处理日志输出、数据记录等场景的必备能力,std::put_time作为C++11标准提供的流操作工具,能够便捷地将时间数据转换为指定格式的字符串。它定义在iomanip头文件中,通过传入时间结构和格式字符串,即可完成自定义格式的时间输出。

std::put_time基本用法
std::put_time的函数原型为:
#include <iostream>
#include <iomanip>
#include <ctime>
int main() {
// 获取当前时间
std::time_t now = std::time(nullptr);
std::tm* local_tm = std::localtime(&now);
// 使用std::put_time格式化输出
std::cout << "当前时间:" << std::put_time(local_tm, "%Y-%m-%d %H:%M:%S") << std::endl;
return 0;
}
上述代码中,首先通过std::time获取当前时间戳,再用std::localtime转换为本地时间结构std::tm,最后通过std::put_time指定格式字符串%Y-%m-%d %H:%M:%S输出年-月-日 时:分:秒格式的时间。
常用格式说明符
std::put_time的格式字符串由普通字符和格式说明符组成,常用说明符如下:
| 说明符 | 含义 | 示例输出 |
|---|---|---|
| %Y | 四位年份 | 2024 |
| %m | 两位月份(01-12) | 03 |
| %d | 两位日期(01-31) | 15 |
| %H | 24小时制小时(00-23) | 14 |
| %M | 分钟(00-59) | 30 |
| %S | 秒(00-60) | 45 |
| %F | 等价于%Y-%m-%d | 2024-03-15 |
| %T | 等价于%H:%M:%S | 14:30:45 |
与chrono库配合使用
C++11引入的chrono库提供了更现代的时间处理接口,结合std::put_time使用时,需要先将chrono的时间点转换为std::tm结构:
#include <iostream>
#include <iomanip>
#include <chrono>
#include <ctime>
int main() {
// 获取当前时间点
auto now = std::chrono::system_clock::now();
// 转换为time_t
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
// 转换为本地时间结构
std::tm local_tm = *std::localtime(&now_time);
// 格式化输出
std::cout << "chrono获取的时间:" << std::put_time(&local_tm, "%Y年%m月%d日 %H时%M分%S秒") << std::endl;
return 0;
}
使用注意事项
- std::localtime不是线程安全函数,多线程场景下建议使用localtime_r(Linux)或localtime_s(Windows)替代。
- 格式字符串中的普通字符会原样输出,比如可以写成
"%Y/%m/%d"得到斜杠分隔的日期格式。 - 如果需要将格式化后的时间保存到字符串而非直接输出,可以配合
std::ostringstream使用:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>
int main() {
std::time_t now = std::time(nullptr);
std::tm* local_tm = std::localtime(&now);
std::ostringstream oss;
oss << std::put_time(local_tm, "%Y-%m-%d %H:%M:%S");
std::string time_str = oss.str();
std::cout << "保存的时间字符串:" << time_str << std::endl;
return 0;
}
通过上述用法,开发者可以灵活使用std::put_time完成各类时间格式化需求,相比传统的strftime函数,它更贴合C++的流操作习惯,使用起来更加便捷。
std::put_timeC++时间格式化chrono修改时间:2026-07-13 20:09:26