boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

c++中怎么获取当前时间_c++获取系统当前时间方法汇总


avatar
作者 2025年10月8日 10

使用std::time和ctime可快速获取当前时间字符串;2. localtime用于分解时间结构体以获取年月日等细节,需注意tm_year和tm_mon的偏移;3. strftime支持自定义格式化输出;4. chrono提供高精度时间处理,适用于毫秒或微秒级需求。

c++中怎么获取当前时间_c++获取系统当前时间方法汇总

在C++中获取系统当前时间有多种方式,不同方法适用于不同场景,比如需要高精度时间、格式化输出,或跨平台兼容性。以下是几种常用的获取当前时间的方法汇总。

1. 使用 std::timestd::ctime

这是最简单的方式,适合获取当前日历时间(以秒为单位)并输出可读字符串。

示例代码:

 #include <iostream><br> #include <ctime><br><br> int main() {<br>     std::time_t now = std::time(nullptr);<br>     std::cout << "当前时间: " << std::ctime(&now);<br>     return 0;<br> } 

说明:返回的是从1970年1月1日以来的秒数,并转换为本地时间的字符串形式,末尾带换行。

立即学习C++免费学习笔记(深入)”;

2. 使用 std::localtime 精细化格式化

如果需要对年、月、日、时、分、秒分别获取,可以使用 localtime 将 time_t 转为结构体 tm。

示例代码:

 #include <iostream><br> #include <ctime><br><br> int main() {<br>     std::time_t now = std::time(nullptr);<br>     std::tm* local = std::localtime(&now);<br><br>     std::cout << "年: " << local->tm_year + 1900<br>               << ", 月: " << local->tm_mon + 1<br>               << ", 日: " << local->tm_mday<br>               << ", 时: " << local->tm_hour<br>               << ", 分: " << local->tm_min<br>               << ", 秒: " << local->tm_sec << std::endl;<br>     return 0;<br> } 

注意:tm_year 是从1900开始计的偏移量,tm_mon 从0开始(0表示1月),需手动加1。

c++中怎么获取当前时间_c++获取系统当前时间方法汇总

麦当秀MindShow AiPPT

麦当秀|MINDSHOW是一款百万用户正在使用的三分钟生成一份PPT的AI应用系统。它利用引领前沿的人工智能技术,能够自动完成演示内容的设计。

c++中怎么获取当前时间_c++获取系统当前时间方法汇总224

查看详情 c++中怎么获取当前时间_c++获取系统当前时间方法汇总

3. 使用 std::strftime 自定义格式输出

想要更灵活地控制时间字符串格式,可以用 strftime

示例代码:

 #include <iostream><br> #include <ctime><br> #include <array><br><br> int main() {<br>     std::time_t now = std::time(nullptr);<br>     std::tm* local = std::localtime(&now);<br><br>     std::array<char, 100> buffer;<br>     std::strftime(buffer.data(), buffer.size(), "%Y-%m-%d %H:%M:%S", local);<br><br>     std::cout << "格式化时间: " << buffer.data() << std::endl;<br>     return 0;<br> } 

常用格式符:
– %Y:四位年份
– %m:两位月份
– %d:两位日期
– %H:%M:%S:时:分:秒

4. C++11 及以上:使用 chrono 高精度时钟

若需要毫秒、微秒级精度,推荐使用 std::chrono 库。

示例:获取当前时间点并转换为 time_t

 #include <iostream><br> #include <chrono><br> #include <ctime><br><br> int main() {<br>     auto now = std::chrono::system_clock::now();<br>     std::time_t now_c = std::chrono::system_clock::to_time_t(now);<br><br>     std::cout << "当前时间: " << std::ctime(&now_c);<br>     return 0;<br> } 

还可以提取毫秒:

 auto now = std::chrono::system_clock::now();<br> auto ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);<br> auto epoch = ms.time_since_epoch();<br> long long milliseconds = epoch.count(); 

基本上就这些常见用法。根据需求选择:简单打印用 ctime,格式化用 strftime,高精度用 chrono。不复杂但容易忽略细节,比如时区和结构体字段偏移。



评论(已关闭)

评论已关闭

text=ZqhQzanResources