使用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 转换为本地时间结构。
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 buffer;
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 buffer;
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 配合动态长度检查。不复杂但容易忽略细节。
以上就是c++++中如何格式化时间输出_c++时间格式化输出方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1476980.html
微信扫一扫
支付宝扫一扫