功能 #442
打开
由 李立奎 在 4 个月 之前添加.
更新于 4 个月 之前.
描述
std::put_time 是 C++ 标准库 <iomanip> 中的一个 I/O 操纵符(manipulator),用于将 std::tm 结构体中的时间信息格式化为字符串,并插入到输出流(如 std::cout)中。
基本语法¶
std::put_time(const std::tm* tmb, const char* format);
-
tmb:指向 std::tm 的指针,表示要格式化的时间。
-
format:格式字符串,类似于 strftime 的格式。
示例代码¶
#include <iostream>
#include <iomanip>
#include <ctime>
int main() {
std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);
std::cout << "当前时间: " << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << std::endl;
return 0;
}
常用格式符(与 strftime 相同)¶
| 格式符 |
含义 |
示例输出 |
%Y |
四位年份 |
2025 |
%m |
两位月份 |
09 |
%d |
两位日期 |
19 |
%H |
24小时制小时 |
14 |
%M |
分钟 |
30 |
%S |
秒 |
45 |
注意事项¶
- 需要包含头文件:
<iomanip> 和 <ctime>。
- 只适用于输出流(如
std::cout、std::ostringstream),不能用于字符串直接构造。
- 如果你需要字符串,可以用
std::ostringstream:
std::ostringstream oss;
oss << std::put_time(&tm, "%Y-%m-%d");
std::string date = oss.str();
如果你有具体的使用场景(比如想格式化毫秒、UTC 时间、跨平台兼容性等),可以继续问我。
格式化毫秒¶
std::put_time 只能格式化到秒,因为它只接受 std::tm,而 std::tm 里 没有毫秒字段。
要输出 毫秒级时间,必须改用 <chrono>(C++11 及以上),手动把“秒以下”部分拼进去。
下面给出 最通用、只依赖标准库 的写法(C++11 起即可编译,跨平台)。
毫秒级时间戳格式化(YYYY-MM-DD HH:MM:SS.fff)¶
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
std::string format_now_with_ms()
{
using clock = std::chrono::system_clock;
auto now = clock::now(); // 时间戳(含毫秒)
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()) % 1000; // 只取毫秒部分
std::time_t tt = clock::to_time_t(now);
std::tm tm{};
#if defined(_WIN32)
localtime_s(&tm, &tt);
#else
localtime_r(&tt, &tm);
#endif
std::ostringstream oss;
oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S"); // 秒级
oss << '.' << std::setw(3) << std::setfill('0') << ms.count(); // 拼毫秒
return oss.str();
}
int main()
{
std::cout << format_now_with_ms() << '\n'; // 2025-09-19 14:37:28.123
}
要点回顾¶
-
std::put_time 只能到秒;毫秒部分靠 std::chrono 自己取。
- 取毫秒:
auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
- 线程安全:用
localtime_r(POSIX)或 localtime_s(MSVC)。
- 需要更高精度(微秒、纳秒)就把
milliseconds 换成 microseconds / nanoseconds,格式宽度相应改成 6 或 9 即可。
需要 UTC、时区、微秒/纳秒版本,或者想封装成一行宏,继续问我!
导出 Atom
PDF