来源:chatGPT
#include <iostream>
#include <chrono>
#include <iomanip>
#include <ctime>
std::string getCurrentTime(std::string fmt) {
// 获取当前时间点
auto now = std::chrono::system_clock::now();
// 转换为时间_t
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
// 转换为 tm 结构
std::tm now_tm = *std::localtime(&now_c);
// 格式化时间为字符串
std::ostringstream oss;
oss << std::put_time(&now_tm, fmt.data());
return oss.str();
}
int main() {
std::string currentTime = getCurrentTime("%Y-%m-%d %H:%M:%S");
std::cout << "当前时间: " << currentTime << std::endl;
return 0;
}