/** * @brief Time unit enum. * */ enum classtimeunit { /** second */ s, /** millisecond */ ms, /** microsecond */ us, };
/** * @brief Format a timestamp to a human-readable string with a given format. * * @param second the timestamp in seconds. * @param local whether to use local time or UTC time, default is local time. * If local is true, the function will format the timestamp to local time, otherwise, it will format the timestamp to UTC time. * @param fmt the format of the formatted string. useage like std::put_time, see https://en.cppreference.com/w/cpp/io/manip/put_time * @return std::string the formatted string. */ std::string fmt_timestamp(uint64_t second, bool local, const std::string &fmt); /** * @brief Format a timestamp to a human-readable string. * * @param second the timestamp in seconds. * @param local whether to use local time or UTC time, default is local time. * If local is true, the function will format the timestamp to local time, otherwise, it will format the timestamp to UTC time. * @return std::string the formatted string. */ std::string fmt_timestamp_s(uint64_t second, bool local = true); /** * @brief Format a timestamp to a human-readable string. * * @param ms the timestamp in milliseconds. * @param local whether to use local time or UTC time, default is local time. * If local is true, the function will format the timestamp to local time, otherwise, it will format the timestamp to UTC time. * @return std::string the formatted string. */ std::string fmt_timestamp_ms(uint64_t ms, bool local = true); /** * @brief Format a timestamp to a human-readable string. * * @param us the timestamp in microseconds. * @param local whether to use local time or UTC time, default is local time. * If local is true, the function will format the timestamp to local time, otherwise, it will format the timestamp to UTC time. * @return std::string the formatted string. */ std::string fmt_timestamp_us(uint64_t us, bool local = true);
std::stringstream ss; ss << std::put_time(&datetime, fmt.c_str()); return ss.str(); }
// 格式化时间戳,second单位:秒 std::string fmt_timestamp_by_unit(uint64_t t, timeunit unit, bool local) { uint64_t s = 0; std::string extension; switch (unit) { case timeunit::s: s = t; break; case timeunit::ms: { s = t / THOUSAND; auto ms = t % THOUSAND; extension += "." + fmt_uint(ms, 3); } break; case timeunit::us: { s = t / MILLION; auto us = t % MILLION; extension += "." + fmt_uint(us, 6); } break; default: break; }
-------------------------------------------TestFormatTime------------------------------------------- current datetime s: 2024-05-19 22:34:34 current datetime s in UTC: 2024/05/19 14:34:34 current datetime ms: 2024-05-19 22:34:34.848 current datetime ms in UTC: 2024-05-19 14:34:34.848 current datetime us: 2024-05-19 22:34:34.848467