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

在C++中输出当前时间日期,常用的方法是使用标准库中的 <chrono> 和 <ctime>。下面介绍几种简单实用的方式。
这是最基础也最常用的方法,通过 std::time 获取当前时间戳,再用 std::localtime 转换为本地时间结构,最后用 std::asctime 或 std::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> 提供了更现代的时间处理方式,结合 <ctime> 仍可方便地格式化输出。
示例代码:
#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++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号