首先使用time.h获取时间戳并格式化输出,再通过chrono库实现高精度时间获取,最后从tm结构提取年月日时分秒,结合两者可满足不同精度需求。

在C++中获取系统当前时间有多种方式,常用的方法包括使用C标准库的time.h和C++11引入的chrono库。下面介绍几种实用且跨平台的获取当前时间的方法。
这是最简单直接的方式,适用于只需要获取当前时间戳或格式化日期时间字符串的场景。
步骤:
<ctime>
std::time()获取当前时间点的时间戳std::localtime()转换为本地时间结构std::strftime()格式化输出
#include <iostream>
#include <ctime>
<p>int main() {
std::time_t now = std::time(nullptr);
std::tm* local = std::localtime(&now);</p><pre class='brush:php;toolbar:false;'>char buffer[100];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local);
std::cout << "当前时间: " << buffer << std::endl;
return 0;}
立即学习“C++免费学习笔记(深入)”;
如果你需要更高精度的时间(如毫秒、微秒),推荐使用std::chrono库。
特点:
time_t互转
#include <iostream>
#include <chrono>
#include <ctime>
<p>int main() {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);</p><pre class='brush:php;toolbar:false;'>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<std::chrono::milliseconds>(
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); <p>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;</p><p>std::cout << "时间: " << year << "-" << month << "-" << day << " " << hour << ":" << minute << ":" << second << std::endl;</p>
基本上就这些常见方法。根据是否需要高精度选择chrono还是time.h,日常开发中两者结合使用也很常见。
以上就是c++++中怎么获取当前时间_C++获取系统当前时间方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号