C++打印当前时间

要在 C++ 中打印当前时间并格式化为 YYYY-MM-DD HH:MM:SS,你可以使用 <chrono>和 <iomanip> 头文件

#include <string>
#include <chrono>
#include <iomanip>
#include <sstream>

// 获取当前时间点
auto now = std::chrono::system_clock::now();
// 将时间点转换为时间_t
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
// 使用 ostringstream 格式化时间并转换为 string
//创建一个输出字符串流对象
std::ostringstream oss;
//将格式化时间插入到 ostringstream 中
oss << std::put_time(std::localtime(&now_c), "%Y-%m-%d %H:%M:%S");
//将 ostringstream 内容转换为 std::string
std::string time_str = oss.str();
// 打印时间
LogUtil::info(TAG,("time_str = " + time_str).c_str());
  1. std::chrono::system_clock::now():获取当前系统时间点。
  2. std::chrono::system_clock::to_time_t(now):将系统时间点转换为 std::time_t 类型。
  3. std::localtime(&now_c):将 std::time_t 转换为本地时间结构体。
  4. std::put_time(…, “%Y-%m-%d %H:%M:%S”):格式化时间并打印为 YYYY-MM-DD HH:MM:SS。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值