首先使用获取时间戳并格式化输出,再结合C++11的实现高精度计时,最后根据场景选择合适方法处理时间操作。
在C++中获取当前系统时间以及进行时间与日期操作,常用的方法是借助
标准库
中的
头文件。该头文件提供了对时间的获取、格式化和转换功能。下面介绍几种常见且实用的操作方法。
获取当前时间戳(秒数)
使用
time()
函数可以获取自1970年1月1日00:00:00 UTC以来经过的秒数,也就是常说的时间戳。
将时间戳转换为可读格式
通过
localtime()
或
gmtime()
可以把时间戳转为本地时间或UTC时间结构体
tm
,再用
asctime()
或
strftime()
格式化输出
。
}立即学习“C++免费学习笔记(深入)”;
%Y
表示四位年份,
%m
是月份,
%d
是日期,
%H:%M:%S
是时分秒。支持多种格式化符号,便于定制输出。
使用C++11及以上 chrono 获取高精度时间
如果需要更高精度的时间(如毫秒、微秒),推荐使用
头文件,它属于C++11标准库的一部分。
Trae win
Trae Windows 官方版本现已全面支持 Win10 和 Win11 系统(64位)。国内开发者可直接访问 Trae 中文官网(trae.cn 或 trae.com.cn),一键下载官方正版 .exe 安装包,享受国内直连的高速稳定体验。安装过程极其简便,双击即可运行,并支持一键无缝导入 VS Code 或 Cursor 的原有主题、快捷键及插件配置。登录支持手机号、微信或稀土掘金账号。内置免费的豆包与 DeepSeek 等顶级大模型,让你开箱即用,轻松开启高效的 AI 智能编程之旅。
下载
}立即学习“C++免费学习笔记(深入)”;
这种方法能精确到毫秒甚至微秒,适合对时间精度要求较高的场景,比如性能计时、日志记录等。
常见用途与建议
在实际开发中,根据需求选择合适的方式:
只需要粗略时间(如日志打点),用
time()
+
strftime()
就足够了
需要毫秒级时间显示,结合
chrono
和
ctime
转换处理
做时间差计算(例如程序运行耗时),优先使用
std::chrono::high_resolution_clock
注意多线程环境下
localtime()
不是线程安全的,可使用
localtime_s
(Windows)或
localtime_r
(Linux)替代
基本上就这些。掌握好这几种方式,就能应对大多数C++中时间和日期的操作需求。
#include
#include
int main() {
std::time_t now = std::time(nullptr);
std::cout << "当前时间戳: " << now << std::endl;
return 0;
}
#include
#include
int main() {
std::time_t now = std::time(nullptr);
std::tm* localTime = std::localtime(&now);
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localTime);
std::cout << "当前本地时间: " << buffer << std::endl;
return 0;
#include
#include
#include
int main() {
auto now = std::chrono::system_clock::now();
std::time_t timeT = std::chrono::system_clock::to_time_t(now);
std::tm* localTime = std::localtime(&timeT);
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localTime);
auto ms = std::chrono::duration_cast(now.time_since_epoch()) % 1000;
std::cout << "当前时间: " << buffer << "." << ms.count() << std::endl;
return 0;
