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

在C++中获取当前系统时间以及进行时间与日期操作,常用的方法是借助标准库中的 <ctime> 头文件。该头文件提供了对时间的获取、格式化和转换功能。下面介绍几种常见且实用的操作方法。
使用 time() 函数可以获取自1970年1月1日00:00:00 UTC以来经过的秒数,也就是常说的时间戳。
#include <ctime>
#include <iostream>
<p>int main() {
std::time_t now = std::time(nullptr);
std::cout << "当前时间戳: " << now << std::endl;
return 0;
}</p>通过 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 << "当前本地时间: " << buffer << std::endl;
return 0;}
立即学习“C++免费学习笔记(深入)”;
%Y 表示四位年份,%m 是月份,%d 是日期,%H:%M:%S 是时分秒。支持多种格式化符号,便于定制输出。
如果需要更高精度的时间(如毫秒、微秒),推荐使用 <chrono> 头文件,它属于C++11标准库的一部分。
#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<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
std::cout << "当前时间: " << buffer << "." << ms.count() << std::endl;
return 0;}
立即学习“C++免费学习笔记(深入)”;
这种方法能精确到毫秒甚至微秒,适合对时间精度要求较高的场景,比如性能计时、日志记录等。
在实际开发中,根据需求选择合适的方式:
基本上就这些。掌握好这几种方式,就能应对大多数C++中时间和日期的操作需求。
以上就是c++++怎么获取当前系统时间_c++时间与日期操作方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号