This commit is contained in:
cxh 2025-11-13 14:09:31 +08:00
parent 5adfe421c7
commit 6cde057e87

View File

@ -4,9 +4,9 @@
#include <chrono> #include <chrono>
#include <cstdio> #include <cstdio>
#include <ctime> #include <ctime>
#include <format>
#include <fstream> #include <fstream>
#include <iomanip> #include <iomanip>
#include <sstream>
std::ofstream Logger::log_file; std::ofstream Logger::log_file;
std::string Logger::current_log_filename; std::string Logger::current_log_filename;
@ -26,14 +26,16 @@ std::string Logger::get_time_string()
using namespace std::chrono; using namespace std::chrono;
auto now = system_clock::now(); auto now = system_clock::now();
auto zt = zoned_time{current_zone(), now}; // 自动使用系统时区Asia/Shanghai zoned_time zt{current_zone(), now};
// 获取毫秒部分 auto local = zt.get_local_time();
auto ms = duration_cast<milliseconds>(zt.get_local_time().time_since_epoch()) % 1000; auto ms = duration_cast<milliseconds>(local.time_since_epoch()) % 1000;
std::time_t t = system_clock::to_time_t(now);
std::tm tm_now = *std::localtime(&t);
// 格式化
std::ostringstream ss; std::ostringstream ss;
ss << format("{:%Y-%m-%d %H:%M:%S}", zt) << '.' << std::setw(3) << std::setfill('0') << ms.count(); ss << std::put_time(&tm_now, "%Y-%m-%d %H:%M:%S") << '.' << std::setw(3) << std::setfill('0') << ms.count();
return ss.str(); return ss.str();
} }
@ -45,10 +47,14 @@ std::string Logger::get_current_time_utc8()
auto now = system_clock::now(); auto now = system_clock::now();
zoned_time zt{current_zone(), now}; zoned_time zt{current_zone(), now};
auto ms = duration_cast<milliseconds>(zt.get_local_time().time_since_epoch()) % 1000; auto local = zt.get_local_time();
auto ms = duration_cast<milliseconds>(local.time_since_epoch()) % 1000;
std::time_t t = system_clock::to_time_t(now);
std::tm tm_now = *std::localtime(&t);
std::ostringstream ss; std::ostringstream ss;
ss << format("{:%Y%m%d%H%M%S}", zt) << std::setw(3) << std::setfill('0') << ms.count(); ss << std::put_time(&tm_now, "%Y%m%d%H%M%S") << std::setw(3) << std::setfill('0') << ms.count();
return ss.str(); return ss.str();
} }