C++中获取系统时间主要有两种方法:一是使用<ctime>的C风格,通过std::time、std::localtime和std::strftime获取并格式化时间;二是C++11引入的<chrono>结合<iomanip>的方式,利用std::chrono::system_clock获取高精度时间,再转换为time_t进行格式化输出。此外可使用std::put_time直接流式输出时间结构,适用于现代C++风格,但需注意std::localtime非线程安全,多线程环境下应使用std::localtime_s或localtime_r。

在C++中获取和格式化系统时间有多种方法,常用的是基于<ctime>头文件的C风格方式,以及C++11引入的<chrono>和<iomanip>结合的方式。下面介绍几种实用且清晰的方法。
这是最传统也是最广泛兼容的方法,适用于大多数C++编译器。
步骤如下:
std::time(nullptr)获取自Unix纪元以来的秒数。std::localtime将其转换为本地时间结构tm。std::strftime格式化输出。// 示例代码
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <ctime>
int main() {
std::time_t now = std::time(nullptr);
std::tm* localTime = std::localtime(&now);
char buffer[100];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localTime);
std::cout << "当前时间: " << buffer << std::endl;
return 0;
}
常用格式符说明:
%Y:四位年份(如2025)%m:月份(01-12)%d:日期(01-31)%H:小时(00-23)%M:分钟(00-59)%S:秒数(00-59)%F:等价于%Y-%m-%d%T:等价于%H:%M:%S如果你需要更高精度或更现代的C++风格,可以使用std::chrono获取时间点,再转换为time_t进行格式化。
// 示例:使用chrono获取当前系统时间
#include <iostream>
#include <chrono>
#include <ctime>
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[100];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localTime);
std::cout << "当前时间: " << buffer << std::endl;
return 0;
}
这种方式适合需要与毫秒、微秒等高精度时间交互的场景,虽然格式化仍依赖ctime,但起点更精确。
如果只是想快速打印时间,可以直接使用std::put_time配合流操作(C++11起支持)。
// 使用std::put_time示例
#include <iostream>
#include <iomanip>
#include <ctime>
int main() {
std::time_t now = std::time(nullptr);
std::tm* localTime = std::localtime(&now);
std::cout << "当前时间: "
<< std::put_time(localTime, "%Y-%m-%d %H:%M:%S")
<< std::endl;
return 0;
}
注意:std::put_time在某些编译器(如MinGW)中可能支持不完整,建议测试环境是否可用。
基本上就这些。根据项目需求选择合适的方法:兼容性优先用ctime,现代风格可尝试chrono+put_time。不复杂但容易忽略时区和线程安全问题,std::localtime不是线程安全的,多线程环境下建议使用std::localtime_s(Windows)或localtime_r(Linux)。
以上就是c++++中如何获取当前时间_C++获取与格式化系统时间方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号