首先使用获取时间戳并格式化输出,再结合C++11的实现高精度计时,最后根据场景选择合适方法处理时间操作。

在C++中获取当前系统时间以及进行时间与日期操作,常用的方法是借助标准库中的
获取当前时间戳(秒数)
使用 time() 函数可以获取自1970年1月1日00:00:00 UTC以来经过的秒数,也就是常说的时间戳。
#include <ctime>
#include <iostream><p>int main() {
std::time_t now = std::time(nullptr);
std::cout </p></iostream></ctime>将时间戳转换为可读格式
通过 localtime() 或 gmtime() 可以把时间戳转为本地时间或UTC时间结构体 tm,再用 asctime() 或 strftime() 格式化输出。
#include <ctime>
#include <iostream><p>int main() {
std::time_t now = std::time(nullptr);
std::tm* localTime = std::localtime(&now);</p>
<pre class="brush:php;toolbar:false;">char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localTime);
std::cout <p>}</p>%Y 表示四位年份,%m 是月份,%d 是日期,%H:%M:%S 是时分秒。支持多种格式化符号,便于定制输出。
使用C++11及以上 chrono 获取高精度时间
如果需要更高精度的时间(如毫秒、微秒),推荐使用
#include <iostream>
#include <chrono>
#include <ctime><p>int main() {
auto now = std::chrono::system_clock::now();
std::time_t timeT = std::chrono::system_clock::to_time_t(now);</p>
<pre class="brush:php;toolbar:false;">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<:chrono::milliseconds>(now.time_since_epoch()) % 1000;
std::cout <p>}</p></:chrono::milliseconds>这种方法能精确到毫秒甚至微秒,适合对时间精度要求较高的场景,比如性能计时、日志记录等。
常见用途与建议
在实际开发中,根据需求选择合适的方式:
- 只需要粗略时间(如日志打点),用 time() + strftime() 就足够了
- 需要毫秒级时间显示,结合 chrono 和 ctime 转换处理
- 做时间差计算(例如程序运行耗时),优先使用 std::chrono::high_resolution_clock
- 注意多线程环境下 localtime() 不是线程安全的,可使用 localtime_s(Windows)或 localtime_r(Linux)替代
基本上就这些。掌握好这几种方式,就能应对大多数C++中时间和日期的操作需求。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











