使用time()和ctime()可快速输出时间字符串,如Mon Apr 5 14:23:10 2025;通过localtime()和strftime()可自定义格式为yyYY-MM-DD HH:MM:SS;结合chrono库可获取毫秒级高精度时间。

在c++中获取当前系统时间并进行格式化输出,通常使用标准库中的 chrono 和 ctime 头文件。下面介绍几种常用方法,涵盖高精度时间和可读格式输出。
使用 time() 和 ctime() 快速获取时间字符串
最简单的方式是使用 time() 获取自 unix 纪元以来的秒数,再用 ctime() 转换为可读字符串:
#include <iostream> #include <ctime> <p>int main() { std::time_t now = std::time(nullptr); std::cout << "当前时间: " << std::ctime(&now); return 0; }</p>
输出示例:
Mon Apr 5 14:23:10 2025
注意:ctime() 返回的字符串末尾带换行符。
使用 tm 结构进行自定义格式化
如果需要控制输出格式(如 YYYY-MM-DD HH:MM:SS),可以使用 localtime() 将 time_t 分解为年、月、日等字段:
#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;'>char buffer[64]; std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local); std::cout << "格式化时间: " << buffer << 'n'; return 0;
}
立即学习“C++免费学习笔记(深入)”;
strftime() 支持多种格式符:
- %Y – 四位年份(2025)
- %m – 月份(01-12)
- %d – 日期(01-31)
- %H – 小时(00-23)
- %M – 分钟(00-59)
- %S – 秒(00-60)
- %A – 星期几全称(Monday)
- %B – 月份全称(January)
使用 chrono 获取高精度时间
C++11 引入的 chrono 库支持毫秒、微秒级时间:
#include <iostream> #include <chrono> #include <ctime> <p>int main() { auto now = std::chrono::system_clock::now(); std::time_t t = std::chrono::system_clock::to_time_t(now);</p><pre class='brush:php;toolbar:false;'>std::tm* local = std::localtime(&t); char buffer[64]; std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local); // 获取毫秒部分 auto ms = std::chrono::duration_cast<std::chrono::milliseconds> (now.time_since_epoch()) % 1000; std::cout << "精确时间: " << buffer << '.' << std::setfill('0') << std::setw(3) << ms.count() << 'n'; return 0;
}
立即学习“C++免费学习笔记(深入)”;
需包含 <iomanip> 以使用 setfill 和 setw 控制输出宽度。
基本上就这些。根据需求选择合适的方法:简单输出用 ctime,格式化用 strftime,高精度用 chrono。