C++如何获取当前系统时间?(代码示例)

C++中获取当前系统时间最推荐使用std::chrono::system_clock::now(),适用于高精度计算;需格式化输出时转为time_t配合std::put_time或C++20的std::format;传统方法time+localtime兼容性好但需注意线程安全。

在C++中获取当前系统时间,最常用且跨平台的方式是使用 (C++11起)或 (传统C风格)。下面给出几种主流方法,按推荐程度排序,并附可直接运行的代码示例。

std::chrono 获取高精度时间点(推荐)

适用于需要毫秒/微秒级精度、或做时间差计算的场景。它返回的是“时间点”(time_point),不是格式化字符串,但更现代、类型安全。

// 示例:获取当前时间点,并转为秒级时间戳(自1970-01-01以来的秒数)

#include 
#include 
#include 

int main() { auto now = std::chrono::system_clock::now(); auto seconds = std::chrono::system_clock::to_time_t(now); std::cout << "当前时间(本地):" << std::ctime(&seconds); // 自动带换行 return 0; }

// 若需毫秒值(整数):

auto ms = std::chrono::duration_cast(now.time_since_epoch()).count();
std::cout << "毫秒时间戳:" << ms << std::endl;

std::time + std::localtimestd::gmtime(兼容性好)

适合需要格式化输出(如“2025-05-20 14:30:45”)的场景。注意:localtime 是本地时区,gmtime 是UTC。

#include 
#include 
#include 
#include 

int main() { std::time_t t = std::time(nullptr); std::tm* lt = std::localtime(&t); // 注意:非线程安全;多线程建议用 localtime_r(POSIX)或 _localtime_s(Windows)

std::ostringstream oss;
oss << std::put_time(lt, "%Y-%m-%d %H:%M:%S");
std::cout << "当前本地时间:" << oss.str() << std::endl;
return 0;

}

⚠️ 提示:std::localtime 返回静态缓冲区指针,不建议在多线程中直接使用;生产环境可用 std::strftime 配合栈上 std::tm 变量避免风险。

std::format(C++20,简洁美观)

如果你的编译器支持 C++20(如 GCC 13+、Clang 15+、MSVC 2025 17.5+),这是最干净的格式化方式:

#include 
#include 
#include 

int main() { auto now = std::chrono::system_clock::now(); std::time_t t = std::chrono::system_clock::to_time_t(now); std::cout << std::format("当前时间:{:%Y-%m-%d %H:%M:%S}", std::chrono::system_clock::to_time_t(now)) << std::endl; return 0; }

基本上就这些。日常开发优先选 std::chrono::system_clock::now(),需要打印就转 time_t 配合 std::put_timestd::format;老项目兼容 C++98/03 可继续用 time + localtime + strftime