C++中获取系统时间常用chrono和ctime;2. chrono精度高、类型安全,适合C++11及以上;3. ctime简单兼容好,适合传统代码;4. 高精度用chrono,快速格式化可用ctime配合strftime;5. 多线程注意localtime线程安全问题。

在C++中获取当前系统时间,常用的方法有两种:使用标准库
使用 获取高精度系统时间
chrono 是C++11引入的时间处理库,提供纳秒级精度,支持时钟、时间点和时间间隔的抽象。
获取当前时间并格式化为年-月-日 时:分:秒:
#include <iostream>
#include <chrono>
#include <iomanip>
#include <sstream>
<p>std::string getCurrentTime() {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);</p><pre class='brush:php;toolbar:false;'>std::stringstream ss;
ss << std::put\_time(std::localtime(&time\_t), "%Y-%m-%d %H:%M:%S");
return ss.str();登录后复制
}
立即学习“C++免费学习笔记(深入)”;
说明:
- system\_clock::now() 获取当前时间点
- to\_time\_t() 转换为传统的 time\_t 类型
- std::put\_time 配合流操作进行格式化输出
- 需要包含
支持 put\_time
若需毫秒或微秒精度,可提取时间点中的额外部分:
标签: c++ 系统时间 linux windows ios win stream 格式化输出 标准库
还木有评论哦,快来抢沙发吧~