C++中获取当前时间常用time.h和chrono库,前者适用于简单时间戳和格式化输出,后者支持毫秒级高精度。使用time(nullptr)获取Unix时间戳,localtime与strftime可自定义格式如YYYY-MM-DD HH:MM:SS;chrono库通过system_clock::now()获取高精度时间,结合duration_cast和put_time实现带毫秒的输出。根据需求选择方法,注意时区影响。

在C++中获取系统当前时间有多种方法,常用的方式包括使用C标准库中的time.h和C++11引入的chrono库。下面介绍几种实用且常见的获取当前时间的方法。
这是最简单直接的方法,适用于只需要获取当前时间戳或格式化日期时间字符串的场景。
示例代码:
#include <iostream>
#include <ctime>
<p>int main() {
std::time_t now = std::time(nullptr);
std::cout << "当前时间: " << std::ctime(&now);
return 0;
}</p>说明:
- std::time(nullptr) 返回自1970年1月1日以来的秒数(Unix时间戳)。
- std::ctime() 将时间转换为可读字符串,末尾带换行符。
如果需要自定义格式(如 YYYY-MM-DD HH:MM:SS),可以使用 localtime 和 strftime。
立即学习“C++免费学习笔记(深入)”;
#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[64];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local);
std::cout << "格式化时间: " << buffer << std::endl;
return 0;}
常见格式符:
- %Y:四位年份
- %m:月份(01-12)
- %d:日期(01-31)
- %H:小时(00-23)
- %M:分钟(00-59)
- %S:秒(00-59)
如果你需要毫秒、微秒级精度的时间,推荐使用 <chrono> 库。
#include <iostream>
#include <chrono>
#include <iomanip>
<p>int main() {
auto now = std::chrono::system_clock::now();
auto seconds = std::chrono::system_clock::to_time_t(now);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>
(now.time_since_epoch()) % 1000;</p><pre class='brush:php;toolbar:false;'>std::cout << "当前时间: " << std::put_time(std::localtime(&seconds), "%Y-%m-%d %H:%M:%S")
<< '.' << std::setfill('0') << std::setw(3) << ms.count() << std::endl;
return 0;}
说明:
- system_clock::now() 获取当前时间点。
- time_since_epoch() 返回从纪元开始的总时长。
- 使用取余操作得到毫秒部分,结合 put_time 格式化输出。
基本上就这些。根据需求选择合适的方法:简单用 time 和 localtime,要精度用 chrono。注意时区问题,localtime 使用本地时区,服务器环境需留意设置。不复杂但容易忽略细节。
以上就是c++++中如何获取当前时间_c++获取系统当前时间方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号