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

在C++中输出当前时间日期,常用的方法是使用标准库中的 和 。下面介绍几种简单实用的方式。
使用 ctime 输出格式化时间
这是最基础也最常用的方法,通过 std::time 获取当前时间戳,再用 std::localtime 转换为本地时间结构,最后用 std::asctime 或 std::strftime 格式化输出。
示例代码:
#include #includeint main() {std::time_t now = std::time(nullptr);std::tm* local = std::localtime(&now);
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及以上)
提供了更现代的时间处理方式,结合 仍可方便地格式化输出。
示例代码:
#include #include #includeint 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);
char buf[64];std::strftime(buf, sizeof(buf), "%F %T", tm_ptr); // %F 等价于 %Y-%m-%d,%T 等价于 %H:%M:%Sstd::cout << "当前时间: " << buf << std::endl;return 0;
}
直接输出年月日时分秒(适合日志等场景)
如果想自己拼接格式,也可以逐个提取字段:
#include #includevoid printCurrentTime() {std::time_t t = std::time(nullptr);std::tm* now = std::localtime(&t);
std::cout <tm_year + 1900) << "-" <tm_mon + 1) << "-" <tm_mday << " " <tm_hour << ":" <tm_min << ":" <tm_sec << std::endl;
}
int main() {printCurrentTime();return 0;}
注意:tm_year 是从1900年开始的偏移量,tm_mon 从0开始(0表示1月),所以要加1。
基本上就这些常见方法。推荐使用 std::strftime 配合 std::time,简洁清晰,控制灵活。
以上就是c++++中如何输出当前时间日期_c++时间日期输出方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1478863.html
微信扫一扫
支付宝扫一扫