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#include int 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 #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* 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:%S std::cout << "当前时间: " << buf << std::endl; return 0;}
直接输出年月日时分秒(适合日志等场景)
如果想自己拼接格式,也可以逐个提取字段:
#include#include void printCurrentTime() { std::time_t t = std::time(nullptr); std::tm* now = std::localtime(&t);
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,简洁清晰,控制灵活。











