c++中获取系统时间并格式化的方法主要使用<chrono>和<ctime>。首先通过std::chrono::system_clock::now()获取当前时间点,再转换为time_t类型,结合std::localtime和std::strftime进行自定义格式输出,如“yyYY-MM-DD HH:MM:SS”。推荐使用strftime支持灵活格式控制,适用于日志命名等场景。注意std::localtime非线程安全,多线程环境下应使用std::localtime_s或std::gmtime_s以避免数据竞争。

C++ 获取系统时间与时间格式化方法
在 C++ 中获取当前时间并进行格式化,常用的方法依赖于标准库中的 <chrono> 和 <ctime>。以下介绍几种实用且现代的实现方式。
使用 chrono 和 ctime 获取当前时间
std::chrono 是 C++11 引入的现代化时间处理库,结合 std::ctime 可以方便地获取和显示当前时间。
- 通过
std::chrono::system_clock::now()获取当前时间点 - 转换为 time_t 类型以便格式化输出
- 使用
std::ctime或std::localtime转换为可读字符串
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream> #include <chrono> #include <ctime> <p>int main() { // 获取当前时间点 auto now = std::chrono::system_clock::now(); // 转换为 time_t std::time_t time_t = std::chrono::system_clock::to_time_t(now); // 格式化输出 std::cout << "当前时间: " << std::ctime(&time_t); return 0; }
手动格式化时间(年-月-日 时:分:秒)
如果需要自定义格式(如 YYYY-MM-DD HH:MM:SS),可以使用 std::localtime 分解时间结构。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#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_time = std::localtime(&time_t);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">char buffer[64]; std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_time); std::cout << "格式化时间: " << buffer << 'n'; return 0;
}
使用 strftime 进行灵活格式化
std::strftime 支持多种格式控制符,适合生成日志文件名或固定格式输出。
- %Y:四位年份
- %m:月份(01-12)
- %d:日期(01-31)
- %H:%M:%S:时:分:秒(24小时制)
- 支持组合输出,例如生成时间戳文件名
常见格式示例:
基本上就这些。使用 chrono 获取时间点,再通过 localtime 和 strftime 格式化,是 C++ 中最常见也最可靠的做法。不复杂但容易忽略细节,比如线程安全问题(std::localtime 非线程安全,多线程建议用 std::localtime_s 或 gmtime_s)。