首页 > 后端开发 > C++ > 正文

c++中如何输出当前时间日期_c++时间日期输出方法

尼克
发布: 2025-10-13 23:54:01
原创
1088人浏览过
C++中输出当前时间常用ctime和chrono库,通过std::time获取时间戳并用std::localtime转换,再用std::strftime格式化输出;或使用std::chrono::system_clock::now()获取高精度时间,结合ctime转换输出;也可直接提取tm结构体成员拼接年月日时分秒,推荐strftime方式简洁灵活。

c++中如何输出当前时间日期_c++时间日期输出方法

在C++中输出当前时间日期,常用的方法是使用标准库中的 <chrono><ctime>。下面介绍几种简单实用的方式。

使用 ctime 输出格式化时间

这是最基础也最常用的方法,通过 std::time 获取当前时间戳,再用 std::localtime 转换为本地时间结构,最后用 std::asctimestd::strftime 格式化输出

示例代码:

#include <iostream>
#include <ctime>
<p>int main() {
std::time_t now = std::time(nullptr);
std::tm* local = std::localtime(&now);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">char buffer[100];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local);
std::cout << "当前时间: " << buffer << std::endl;

return 0;
登录后复制

}

说明:
%Y 年份(四位),%m 月份,%d 日期,%H 小时(24小时制),%M 分钟,%S 秒。

立即学习C++免费学习笔记(深入)”;

使用 chrono 高精度时间(C++11及以上)

<chrono> 提供了更现代的时间处理方式,结合 <ctime> 仍可方便地格式化输出。

美间AI
美间AI

美间AI:让设计更简单

美间AI 45
查看详情 美间AI

示例代码:

#include <iostream>
#include <chrono>
#include <ctime>
<p>int main() {
auto now = std::chrono::system_clock::now();
std::time_t time_t = std::chrono::system_clock::to_time_t(now);
std::tm* tm_ptr = std::localtime(&time_t);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">char buf[64];
std::strftime(buf, sizeof(buf), "%F %T", tm_ptr); // %F 等价于 %Y-%m-%d,%T 等价于 %H:%M:%S
std::cout << "当前时间: " << buf << std::endl;

return 0;
登录后复制

}

直接输出年月日时分秒(适合日志等场景)

如果想自己拼接格式,也可以逐个提取字段:

#include <iostream>
#include <ctime>
<p>void printCurrentTime() {
std::time_t t = std::time(nullptr);
std::tm* now = std::localtime(&t);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">std::cout << (now->tm_year + 1900) << "-"
           << (now->tm_mon + 1) << "-"
           << now->tm_mday << " "
           << now->tm_hour << ":"
           << now->tm_min << ":"
           << now->tm_sec << std::endl;
登录后复制

}

int main() { printCurrentTime(); return 0; }

注意:tm_year 是从1900年开始的偏移量,tm_mon 从0开始(0表示1月),所以要加1。

基本上就这些常见方法。推荐使用 std::strftime 配合 std::time,简洁清晰,控制灵活。

以上就是c++++中如何输出当前时间日期_c++时间日期输出方法的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号