C++获取当前时间戳_C++获取系统时间及格式化

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

在C++中获取当前时间戳以及系统时间并进行格式化,是开发中常见的需求,比如用于日志记录、性能监控或文件命名等场景。下面介绍几种常用的方法,涵盖从简单的时间戳获取到格式化输出的完整流程。

C++获取当前时间戳(秒级/毫秒级)

使用 std::chrono 是现代C++推荐的方式,可以精确获取时间戳。

秒级时间戳:

#include 
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::duration_cast(now.time_since_epoch()).count();
// 输出示例:1718000000

毫秒级时间戳:

auto timestamp_ms = std::chrono::duration_cast(now.time_since_epoch()).count();
// 输出示例:1718000000123

获取系统时间并格式化为可读字符串

结合 std::chronostd::ctimestd::strftime 可将时间转换为年-月-日 时:分:秒 格式。

#include 
#include 
#include 

auto now = std::chrono::system_clock::now(); auto time_t = std::chrono::system_clock::to_time_t(now);

// 转换为本地时间 std::tm* local_tm = std::localtime(&time_t);

char buffer[80]; std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_tm);

std::cout << "当前时间: " << buffer << std::endl; // 输出示例:2024-06-10 15:30:45

常用格式化符号说明:

  • %Y:四位年份(如 2025)
  • %m:月份(01-12)
  • %d:日期(01-31)
  • %H:小时(00-23)
  • %M:分钟(00-59)
  • %S:秒(00-59)
  • %F:等价于 %Y-%m-%d
  • %T:等价于 %H:%M:%S

组合使用:获取带毫秒的格式化时间

如果需要显示到毫秒级别,需手动提取毫秒部分。

#include 
#include 
#include 
#include 

auto now = std::chrono::system_clock::now(); auto time_t = std::chrono::system_clock::to_time_t(now); auto ms = std::chrono::duration_cast(now.time_since_epoch()) % 1000;

std::tm* tm = std::localtime(&time_t);

char buffer[80]; std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm);

std::cout << std::fixed << std::setfill('0') << std::setw(3) << ms.count(); // 输出示例:2024-06-10 15:30:45.123

传统方法:使用 time() 和 localtime()

适用于C风格代码或对性能要求不高的场景。

#include 
#include 

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 更简洁,适合基本格式输出。根据项目需求选择即可。