要在 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());
- std::chrono::system_clock::now():获取当前系统时间点。
- std::chrono::system_clock::to_time_t(now):将系统时间点转换为 std::time_t 类型。
- std::localtime(&now_c):将 std::time_t 转换为本地时间结构体。
- std::put_time(…, “%Y-%m-%d %H:%M:%S”):格式化时间并打印为 YYYY-MM-DD HH:MM:SS。