跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

c++中怎么获取当前时间_C++获取系统当前时间方法

首先使用time.h获取时间戳并格式化输出,再通过chrono库实现高精度时间获取,最后从tm结构提取年月日时分秒,结合两者可满足不同精度需求。 在C++中获取系统当前时间有多种方式,常用的方法包括使用C 标准库 的
time.h
和C++11引入的
chrono
库。下面介绍几种实用且跨平台的获取当前时间的方法。 使用time.h获取当前时间(C风格) 这是最简单直接的方式,适用于只需要获取当前时间戳或格式化日期时间字符串的场景。 步骤: 包含头文件
调用
std::time()
获取当前时间点的时间戳 使用
std::localtime()
转换为本地时间结构 用
std::strftime()
格式化输出
#include #include

int main() { std::time_t now = std::time(nullptr); std::tm* local = std::localtime(&now);

char buffer[100];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local);
std::cout << "当前时间: " << buffer << std::endl;

return 0;
}立即学习“C++免费学习笔记(深入)”; 使用chrono库获取高精度时间(C++11及以上) 如果你需要更高精度的时间(如毫秒、微秒),推荐使用
std::chrono
库。 C函数速查手册(CHM版) C函数速查手册(CHM版) 下载 特点: 支持纳秒级精度 类型安全,避免错误 可与
time_t
互转
#include #include #include

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);
std::cout << "当前时间: " 
          << std::put_time(tm, "%Y-%m-%d %H:%M:%S") << std::endl;

// 获取毫秒
auto ms = std::chrono::duration_cast(
    now.time_since_epoch()) % 1000;
std::cout << "毫秒部分: " << ms.count() << std::endl;

return 0;
}立即学习“C++免费学习笔记(深入)”; 格式化输出年月日时分秒 有时需要分别获取年、月、日等字段,可以直接从
std::tm
结构中提取。
std::time_t now = std::time(nullptr); std::tm* local = std::localtime(&now);

int year = local->tm_year + 1900; // 从1900年开始计数 int month = local->tm_mon + 1; // 月份从0开始 int day = local->tm_mday; int hour = local->tm_hour; int minute = local->tm_min; int second = local->tm_sec;

std::cout << "时间: " << year << "-" << month << "-" << day << " " << hour << ":" << minute << ":" << second << std::endl;

基本上就这些常见方法。根据是否需要高精度选择
chrono
还是
time.h
,日常开发中两者结合使用也很常见。

相关文章