使用time()和ctime()可快速输出时间字符串,如Mon Apr 5 14:23:10 2025;通过localtime()和strftime()可自定义格式为YYYY-MM-DD HH:MM:SS;结合chrono库可获取毫秒级高精度时间。

在C++中获取当前系统时间并进行格式化输出,通常使用标准库中的 chrono 和 ctime 头文件。下面介绍几种常用方法,涵盖高精度时间和可读格式输出。
最简单的方式是使用 time() 获取自 Unix 纪元以来的秒数,再用 ctime() 转换为可读字符串:
#include <iostream>
#include <ctime>
<p>int main() {
std::time_t now = std::time(nullptr);
std::cout << "当前时间: " << std::ctime(&now);
return 0;
}</p>输出示例:
Mon Apr 5 14:23:10 2025
注意:ctime() 返回的字符串末尾带换行符。
如果需要控制输出格式(如 YYYY-MM-DD HH:MM:SS),可以使用 localtime() 将 time_t 分解为年、月、日等字段:
#include <iostream>
#include <ctime>
<p>int main() {
std::time_t now = std::time(nullptr);
std::tm* local = std::localtime(&now);</p><pre class='brush:php;toolbar:false;'>char buffer[64];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local);
std::cout << "格式化时间: " << buffer << '\n';
return 0;}
立即学习“C++免费学习笔记(深入)”;
strftime() 支持多种格式符:
C++11 引入的 chrono 库支持毫秒、微秒级时间:
#include <iostream>
#include <chrono>
#include <ctime>
<p>int main() {
auto now = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(now);</p><pre class='brush:php;toolbar:false;'>std::tm* local = std::localtime(&t);
char buffer[64];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local);
// 获取毫秒部分
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>
(now.time_since_epoch()) % 1000;
std::cout << "精确时间: " << buffer
<< '.' << std::setfill('0') << std::setw(3) << ms.count() << '\n';
return 0;}
立即学习“C++免费学习笔记(深入)”;
需包含 <iomanip> 以使用 setfill 和 setw 控制输出宽度。
基本上就这些。根据需求选择合适的方法:简单输出用 ctime,格式化用 strftime,高精度用 chrono。
以上就是c++++中如何获取当前系统时间_c++获取系统时间与格式化输出方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号