使用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 转换为本地时间结构。
int main() {
std::time_t now = std::time(nullptr);
std::tm* localTime = std::localtime(&now);
// 接下来可以格式化输出
}
strftime 是C风格函数,功能强大,支持多种格式控制符,能将 tm 结构格式化为字符串。
立即学习“C++免费学习笔记(深入)”;
常见格式控制符:
int main() {
std::time_t now = std::time(nullptr);
std::tm* localTime = std::localtime(&now);
std::array<char, 100> buffer;
std::size_t len = std::strftime(buffer.data(), buffer.size(), "%Y-%m-%d %H:%M:%S", localTime);
if (len != 0) {
std::cout << "当前时间: " << buffer.data() << std::endl;
}
return 0;
}
输出示例:
当前时间: 2024-05-30 14:30:00
如果你使用的是 C++11 或更高版本,可以用 std::chrono 获取高精度时间,但最终仍需转为 time_t 才能用 strftime 格式化。
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<char, 100> buffer;
std::strftime(buffer.data(), buffer.size(), "%Y-%m-%d %H:%M:%S", localTime);
std::cout << "格式化时间: " << buffer.data() << std::endl;
return 0;
}
这种方式更现代,适合需要高精度时间记录的场景。
基本上就这些。掌握 std::time、std::localtime 和 strftime 的组合使用,就能灵活输出任意格式的时间字符串。注意缓冲区大小避免溢出,推荐使用 std::array 或 std::string 配合动态长度检查。不复杂但容易忽略细节。
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号