/* * @Author: yangzilong * @Date: 2021-12-17 17:45:43 * @Last Modified by: yangzilong * @Email: yangzilong@objecteye.com * @Description: */ #ifndef __OLFIELD_UTILS_TIMER_HPP__ #define __OLFIELD_UTILS_TIMER_HPP__ #include #include #include #include #include #include #include #include using namespace std; namespace helpers { namespace timer { template static inline long long get_timestamp() { auto now = std::chrono::system_clock::now(); return std::chrono::duration_cast(now.time_since_epoch()).count(); } static long long get_cur_time_ms(){ chrono::time_point tpMicro = chrono::time_point_cast(chrono::system_clock::now()); return tpMicro.time_since_epoch().count(); } static std::string get_date(bool with_time = false) { std::chrono::system_clock::time_point t = std::chrono::system_clock::now(); auto as_time_t = std::chrono::system_clock::to_time_t(t); struct tm tm; #if defined(WIN32) || defined(_WINDLL) localtime_s(&tm, &as_time_t); // win api thread safe, but std::localtime can't thread safe. #else localtime_r(&as_time_t, &tm); // linux api thread safe. #endif char buf[256]{0}; if (with_time) snprintf(buf, sizeof(buf), "%04d%02d%02d_%02d%02d%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); else snprintf(buf, sizeof(buf), "%04d%02d%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); return std::string(buf); } static long long get_ts_by_day_ms(int year, int month, int day) { // 初始化tm结构体 std::tm t = {}; t.tm_year = year - 1900; // 年从1900年开始计数 t.tm_mon = month - 1; // 月份从0开始计数,3月是第4个月 t.tm_mday = day; // 日 t.tm_hour = 0; // 小时 t.tm_min = 0; // 分钟 t.tm_sec = 0; // 秒 // 使用mktime转换为time_t(如果需要) std::time_t timestamp = std::mktime(&t); // 或者直接使用下面的chrono方法跳过这一步 if (timestamp == -1) { return -1; // 或者抛出异常等错误处理方式 } // 使用chrono转换(如果不需要先转换为time_t) auto timepoint = std::chrono::system_clock::from_time_t(timestamp); auto duration = timepoint.time_since_epoch(); auto ms = std::chrono::duration_cast(duration).count(); return ms; } } // namespace timer } // namespace helpers #endif // __OLFIELD_UTILS_TIMER_HPP__