使用获取当前时间戳并转换为本地时间结构,输出年月日时分秒格式的时间。

在C++中获取系统当前时间,常用的方法是使用标准库中的 和 。下面介绍几种实用且清晰的方式,帮助你快速获取当前时间。
使用 获取日期和时间
这是最传统、兼容性最好的方式,适合获取年月日时分秒格式的时间。
示例代码:
#include
#include
int main() {
std::time_t now = std::time(nullptr); // 获取当前时间戳
std::tm* localTime = std::localtime(&now); // 转换为本地时间结构
// 输出格式化时间
std::cout <tm_year + 1900) << "-"
<tm_mon + 1) << "-"
<tm_mday << " "
<tm_hour << ":"
<tm_min << ":"
<tm_sec << std::endl;
return 0;
}
说明:std::localtime 返回的是本地时间,注意 tm_year 是从1900年开始计算的,tm_mon 从0开始(0表示1月)。
立即学习“C++免费学习笔记(深入)”;
使用 高精度获取时间
如果你需要更高精度的时间(比如毫秒或微秒),推荐使用 C++11 引入的 库。
示例代码:
#include
#include
#include
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);
std::cout << "当前时间: " << std::put_time(localTime, "%Y-%m-%d %H:%M:%S") << std::endl;
// 获取毫秒
auto ms = std::chrono::duration_cast
(now.time_since_epoch()) % 1000;
std::cout << "毫秒部分: " << ms.count() << "ms" << std::endl;
return 0;
}
说明:这种方式可以精确到毫秒甚至微秒,适用于日志记录、性能测试等场景。
格式化输出时间字符串
你可以将时间输出为指定格式的字符串,便于日志或文件命名。
示例:生成 YYYYMMDD_HHMMSS 格式的时间字符串
#include
#include
#include
#include
std::string getCurrentTimeStr() {
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);
std::ostringstream oss;
oss << std::put_time(&localTime, "%Y%m%d_%H%M%S");
return oss.str();
}
int main() {
std::cout << "文件名时间戳: " << getCurrentTimeStr() << std::endl;
return 0;
}
说明:std::put_time 配合 ostringstream 可以灵活生成各种格式的时间字符串。
基本上就这些。根据你的需求选择合适的方法:简单用 ctime,高精度用 chrono。两种方式都稳定可靠,广泛用于实际项目中。
以上就是c++++如何获取当前系统时间_c++获取系统当前时间教程的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1481146.html
微信扫一扫
支付宝扫一扫