
在C++中获取当前系统时间并进行格式化输出,常用的方法依赖于标准库中的 <chrono> 和 <ctime>。下面介绍几种实用的方式。
使用 std::time 获取从1970年1月1日以来的秒数,适合简单的时间戳记录。
示例代码:
#include <iostream>
#include <ctime>
int main() {
std::time_t now = std::time(nullptr);
std::cout << "当前时间戳: " << now << std::endl;
return 0;
}
结合 std::localtime 将 time_t 转换为本地时间结构,并用 std::strftime 格式化输出。
示例代码:
#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:四位年份
- %m:月份(01-12)
- %d:日期(01-31)
- %H:小时(00-23)
- %M:分钟(00-59)
- %S:秒(00-60)
如果需要更高精度(如毫秒、微秒),推荐使用 <chrono> 库。
立即学习“C++免费学习笔记(深入)”;
示例代码(获取毫秒级时间):
#include <iostream>
#include <chrono>
#include <ctime>
int main() {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
std::tm* tm = std::localtime(&time_t);
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm);
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() << std::endl;
return 0;
}
注意:需包含 <iomanip> 以使用 std::setfill 和 std::setw 补零输出毫秒。
基本上就这些方法,根据是否需要高精度选择 time_t 或 chrono。格式化输出统一推荐 strftime,简洁可控。
以上就是c++++怎么获取当前系统时间_c++获取系统时间与格式化方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号