使用std::chrono可获取秒级和毫秒级时间戳;2. 结合std::strftime可格式化输出年-月-日 时:分:秒;3. 手动提取毫秒部分可实现带毫秒的时间字符串;4. 传统方法用time()和localtime()适合简单场景,但线程不安全。

在C++中获取当前时间戳以及系统时间并进行格式化,是开发中常见的需求,比如用于日志记录、性能监控或文件命名等场景。下面介绍几种常用的方法,涵盖从简单的时间戳获取到格式化输出的完整流程。
使用 std::chrono 是现代C++推荐的方式,可以精确获取时间戳。
秒级时间戳:#include <chrono> auto now = std::chrono::system_clock::now(); auto timestamp = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count(); // 输出示例:1718000000
毫秒级时间戳:
auto timestamp_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); // 输出示例:1718000000123
结合 std::chrono 和 std::ctime 或 std::strftime 可将时间转换为年-月-日 时:分:秒 格式。
立即学习“C++免费学习笔记(深入)”;
#include <iostream> #include <chrono> #include <ctime> <p>auto now = std::chrono::system_clock::now(); auto time_t = std::chrono::system_clock::to_time_t(now);</p><p>// 转换为本地时间 std::tm* local_tm = std::localtime(&time_t);</p><p>char buffer[80]; std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_tm);</p><p>std::cout << "当前时间: " << buffer << std::endl; // 输出示例:2024-06-10 15:30:45
常用格式化符号说明:
如果需要显示到毫秒级别,需手动提取毫秒部分。
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
<p>auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;</p><p>std::tm* tm = std::localtime(&time_t);</p><p>char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm);</p><p>std::cout << std::fixed << std::setfill('0') << std::setw(3) << ms.count();
// 输出示例:2024-06-10 15:30:45.123
适用于C风格代码或对性能要求不高的场景。
#include <ctime> #include <iostream> <p>std::time_t t = std::time(nullptr); char* str = std::ctime(&t); // 包含换行符 str[strcspn(str, "\n")] = 0; // 去除换行 std::cout << "当前时间: " << str << std::endl;
注意:std::ctime 返回的是静态缓冲区内容,线程不安全,多线程环境下建议使用 localtime_s(Windows)或 localtime_r(Linux)。
基本上就这些。用 std::chrono 更现代、灵活,适合高精度需求;而传统 time + strftime 更简洁,适合基本格式输出。根据项目需求选择即可。
以上就是C++获取当前时间戳_C++获取系统时间及格式化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号