1#include <CS2Kit/Utils/TimeUtils.hpp>
11int64_t TimeUtils::Now()
13 auto now = std::chrono::system_clock::now();
14 return std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
17int64_t TimeUtils::ParseDuration(
const std::string& duration)
19 std::string lower = duration;
20 std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
22 if (lower.empty() || lower ==
"0" || lower ==
"perm" || lower ==
"permanent")
25 std::regex pattern(R
"((\d+)([smhdw]))");
27 if (std::regex_match(lower, matches, pattern))
31 int64_t value = std::stoll(matches[1].str());
32 switch (matches[2].str()[0])
37 return value * SecondsPerMinute;
39 return value * SecondsPerHour;
41 return value * SecondsPerDay;
43 return value * SecondsPerWeek;
56 return std::stoll(duration);
64std::string TimeUtils::FormatDuration(int64_t seconds)
69 if (seconds % SecondsPerWeek == 0 && seconds >= SecondsPerWeek)
71 int64_t w = seconds / SecondsPerWeek;
72 return std::format(
"{} week{}", w, w > 1 ?
"s" :
"");
74 if (seconds % SecondsPerDay == 0 && seconds >= SecondsPerDay)
76 int64_t d = seconds / SecondsPerDay;
77 return std::format(
"{} day{}", d, d > 1 ?
"s" :
"");
79 if (seconds % SecondsPerHour == 0 && seconds >= SecondsPerHour)
81 int64_t h = seconds / SecondsPerHour;
82 return std::format(
"{} hour{}", h, h > 1 ?
"s" :
"");
84 if (seconds % SecondsPerMinute == 0 && seconds >= SecondsPerMinute)
86 int64_t m = seconds / SecondsPerMinute;
87 return std::format(
"{} minute{}", m, m > 1 ?
"s" :
"");
89 return std::format(
"{} second{}", seconds, seconds > 1 ?
"s" :
"");
92std::string TimeUtils::FormatTimestamp(int64_t timestamp)
97 std::time_t time =
static_cast<std::time_t
>(timestamp);
100 localtime_s(&tm, &time);
102 localtime_r(&time, &tm);
104 return std::format(
"{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
105 tm.tm_hour, tm.tm_min, tm.tm_sec);
108bool TimeUtils::IsExpired(int64_t expiresAt)
112 return Now() >= expiresAt;
115int64_t TimeUtils::GetExpirationTime(int64_t durationSeconds)
117 if (durationSeconds == 0)
119 return Now() + durationSeconds;