C++中显示当前时间的几种方法:使用 time() 获取时间戳使用 std::chrono 类获取系统时间使用第三方库(如 Boost.Date_Time)

如何在 C++ 中显示当前时间
在 C++ 中显示当前时间的方法有几种:
1. 使用标准库函数 time()
#include#include int main() { time_t now = time(0); std::cout << "Current time: " << ctime(&now); return 0; }
2. 使用类 std::chrono
立即学习“C++免费学习笔记(深入)”;
#include#include int main() { auto now = std::chrono::system_clock::now(); auto time_t_now = std::chrono::system_clock::to_time_t(now); std::cout << "Current time: " << ctime(&time_t_now); return 0; }
3. 使用第三方库
有许多第三方库可以帮助你显示当前时间,例如 Boost.Date_Time:
#include#include int main() { boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); std::cout << "Current time: " << now; return 0; }











