答案:C++中获取当前时间常用和,通过std::chrono::system_clock::now()获取高精度时间,或使用time()结合localtime()与strftime格式化输出年月日时分秒。

在C++中获取当前时间有多种方法,常用的方式依赖于标准库中的
使用 chrono 获取高精度时间
- 通过 std::chrono::system_clock::now() 获取当前时间点
- 可转换为 time_t 格式用于格式化输出
示例代码:
#include#include #include int main() { auto now = std::chrono::system_clock::now(); std::time_t time_t_now = std::chrono::system_clock::to_time_t(now); std::cout << "当前时间: " << std::ctime(&time_t_now); return 0; }
使用 ctime 获取简单日期时间
如果只需要简单的年月日时分秒格式,可以直接使用
立即学习“C++免费学习笔记(深入)”;
- time(nullptr) 获取当前时间的秒数(自1970年起)
- localtime() 将时间转换为本地时间结构体
示例代码:
#include#include int main() { std::time_t now = std::time(nullptr); std::tm* local = std::localtime(&now);
char buffer[80]; std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local); std::cout << "当前时间: " << buffer << std::endl; return 0;}
格式化输出年月日时分秒
使用 std::strftime 可以灵活控制时间输出格式。
常见格式符:
- %Y:四位年份
- %m:月份(01-12)
- %d:日期(01-31)
- %H:小时(00-23)
- %M:分钟(00-59)
- %S:秒数(00-59)
上面例子中 std::strftime 就是按指定格式写入字符串。
基本上就这些。根据是否需要高精度或仅需可读时间,选择合适的方法即可。不复杂但容易忽略细节,比如时区和线程安全。











