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>。以下介绍几种实用且现代的实现方式。
std::chrono 是 C++11 引入的现代化时间处理库,结合 std::ctime 可以方便地获取和显示当前时间。
std::chrono::system_clock::now() 获取当前时间点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;}
std::strftime 支持多种格式控制符,适合生成日志文件名或固定格式输出。
常见格式示例:
std::strftime(buffer, 100, "%Y%m%d_%H%M%S", tm_time); // 输出:20250405_143022
基本上就这些。使用 chrono 获取时间点,再通过 localtime 和 strftime 格式化,是 C++ 中最常见也最可靠的做法。不复杂但容易忽略细节,比如线程安全问题(std::localtime 非线程安全,多线程建议用 std::localtime_s 或 gmtime_s)。
以上就是C++ 如何获取当前时间_C++ 获取系统时间与时间格式化方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号