使用C++格式化时间需结合chrono、ctime与strftime函数,先获取当前时间戳并转为本地tm结构,再用strftime按%Y-%m-%d %H:%M:%S等格式输出到缓冲区,推荐使用std::array防溢出。

在C++中格式化时间输出,通常使用标准库中的 chrono 和 ctime 头文件配合 strftime 函数来实现。下面介绍几种常用方法,帮助你将时间以指定格式输出,比如 "2024-05-30 14:30:00" 这样的形式。
获取当前时间并转换为本地时间
要格式化输出时间,先要获取当前时间点,并将其转换为可读的结构化时间(struct tm):
使用 std::time 获取当前时间戳,再用 std::localtime 转换为本地时间结构。
Python v2.4版chm格式的中文手册,内容丰富全面,不但是一本手册,你完全可以把她作为一本Python的入门教程,教你如何使用Python解释器、流程控制、数据结构、模板、输入和输出、错误和异常、类和标准库详解等方面的知识技巧。同时后附的手册可以方便你的查询。
include iostream>
include
int main() {
std::time_t now = std::time(nullptr);
std::tm* localTime = std::localtime(&now);
// 接下来可以格式化输出
}
使用 strftime 格式化时间
strftime 是C风格函数,功能强大,支持多种格式控制符,能将 tm 结构格式化为字符串。
立即学习“C++免费学习笔记(深入)”;
常见格式控制符:
- %Y - 四位年份(如 2024)
- %m - 月份(01-12)
- %d - 日期(01-31)
- %H - 小时(00-23)
- %M - 分钟(00-59)
- %S - 秒数(00-60)
- %F - 等价于 %Y-%m-%d(ISO 日期格式)
- %T - 等价于 %H:%M:%S
include stream>
include
include
int main() {
std::time_t now = std::time(nullptr);
std::tm* localTime = std::localtime(&now);
std::array
std::size_t len = std::strftime(buffer.data(), buffer.size(), "%Y-%m-%d %H:%M:%S", localTime);
if (len != 0) {
std::cout
}
return 0;
}
输出示例:
当前时间: 2024-05-30 14:30:00
C++11 chrono 高精度时间结合格式化
如果你使用的是 C++11 或更高版本,可以用 std::chrono 获取高精度时间,但最终仍需转为 time_t 才能用 strftime 格式化。
include
include
include
include
int main() {
auto now = std::chrono::system_clock::now();
std::time_t time_t = std::chrono::system_clock::to_time_t(now);
std::tm* localTime = std::localtime(&time_t);
std::array
std::strftime(buffer.data(), buffer.size(), "%Y-%m-%d %H:%M:%S", localTime);
std::cout
return 0;
}
这种方式更现代,适合需要高精度时间记录的场景。
基本上就这些。掌握 std::time、std::localtime 和 strftime 的组合使用,就能灵活输出任意格式的时间字符串。注意缓冲区大小避免溢出,推荐使用 std::array 或 std::string 配合动态长度检查。不复杂但容易忽略细节。










