81 lines
2.1 KiB
C++
81 lines
2.1 KiB
C++
#pragma once
|
||
|
||
#include <limits.h>
|
||
#include <unistd.h>
|
||
|
||
#include <chrono>
|
||
#include <ctime>
|
||
#include <filesystem>
|
||
#include <fstream>
|
||
#include <iomanip>
|
||
#include <sstream>
|
||
#include <string>
|
||
|
||
namespace common
|
||
{
|
||
|
||
// 获取当前北京时间字符串 (精确到毫秒)
|
||
inline std::string get_current_time_string()
|
||
{
|
||
using namespace std::chrono;
|
||
auto now = system_clock::now();
|
||
auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
|
||
|
||
// 先转 UTC
|
||
auto t = system_clock::to_time_t(now);
|
||
std::tm utc_tm = *std::gmtime(&t);
|
||
|
||
utc_tm.tm_hour += 8;
|
||
mktime(&utc_tm);
|
||
|
||
std::ostringstream oss;
|
||
oss << std::put_time(&utc_tm, "%Y-%m-%d %H:%M:%S") << '.' << std::setw(3) << std::setfill('0') << ms.count();
|
||
return oss.str();
|
||
}
|
||
|
||
// 获取当前日期字符串 (仅日期,用于日志文件名)
|
||
inline std::string get_current_date_string()
|
||
{
|
||
using namespace std::chrono;
|
||
auto now = system_clock::now();
|
||
auto t = system_clock::to_time_t(now);
|
||
|
||
// 转成 UTC
|
||
std::tm utc_tm = *std::gmtime(&t);
|
||
|
||
// UTC + 8 小时
|
||
utc_tm.tm_hour += 8;
|
||
mktime(&utc_tm); // 自动修正日期
|
||
|
||
std::ostringstream oss;
|
||
oss << std::put_time(&utc_tm, "%Y-%m-%d");
|
||
return oss.str();
|
||
}
|
||
|
||
// 获取文件大小
|
||
inline size_t get_file_size(const std::string& filename)
|
||
{
|
||
std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
|
||
return in.is_open() ? static_cast<size_t>(in.tellg()) : 0;
|
||
}
|
||
|
||
// 获取可执行文件目录下的文件完整路径
|
||
inline std::string get_executable_file_path(const std::string& filename)
|
||
{
|
||
char result[PATH_MAX];
|
||
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
|
||
std::string path(result, count);
|
||
auto dir = path.substr(0, path.find_last_of('/'));
|
||
if (dir.back() != '/') dir += '/';
|
||
return dir + filename;
|
||
}
|
||
|
||
// 获取当前毫秒时间戳(steady_clock,不受系统时间影响)
|
||
inline uint64_t get_timestamp_ms()
|
||
{
|
||
using namespace std::chrono;
|
||
return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
|
||
}
|
||
|
||
} // namespace common
|