| 2 | 1 #include "time_utils.h" | 
|  | 2 #include <string> | 
|  | 3 #include <cstdint> | 
|  | 4 #include <cmath> | 
|  | 5 #include <ctime> | 
|  | 6 #include <cassert> | 
|  | 7 | 
|  | 8 namespace Time { | 
|  | 9 | 
|  | 10 Duration::Duration(int64_t l) { | 
|  | 11 	length = l; | 
|  | 12 } | 
|  | 13 | 
|  | 14 std::string Duration::AsRelativeString() { | 
|  | 15 	std::string result; | 
|  | 16 | 
|  | 17 	auto get = [](int64_t val, const std::string& s, const std::string& p) { | 
|  | 18 		return std::to_string(val) + " " + (val == 1 ? s : p); | 
|  | 19 	}; | 
|  | 20 | 
|  | 21 	if (InSeconds() < 60) | 
|  | 22 		result = get(InSeconds(), "second", "seconds"); | 
|  | 23 	else if (InMinutes() < 60) | 
|  | 24 		result = get(InMinutes(), "minute", "minutes"); | 
|  | 25 	else if (InHours() < 24) | 
|  | 26 		result = get(InHours(), "hour", "hours"); | 
|  | 27 	else if (InDays() < 28) | 
|  | 28 		result = get(InDays(), "day", "days"); | 
|  | 29 	else if (InDays() < 365) | 
|  | 30 		result = get(InDays()/30, "month", "months"); | 
|  | 31 	else | 
|  | 32 		result = get(InDays()/365, "year", "years"); | 
|  | 33 | 
|  | 34 	if (length < 0) | 
|  | 35 		result = "In " + result; | 
|  | 36 	else | 
|  | 37 		result += " ago"; | 
|  | 38 | 
|  | 39 	return result; | 
|  | 40 } | 
|  | 41 | 
|  | 42 int64_t Duration::InSeconds() { | 
|  | 43 	return length; | 
|  | 44 } | 
|  | 45 | 
|  | 46 int64_t Duration::InMinutes() { | 
|  | 47 	return std::llround((double)length / 60.0); | 
|  | 48 } | 
|  | 49 | 
|  | 50 int64_t Duration::InHours() { | 
|  | 51 	return std::llround((double)length / 3600.0); | 
|  | 52 } | 
|  | 53 | 
|  | 54 int64_t Duration::InDays() { | 
|  | 55 	return std::llround((double)length / 86400.0); | 
|  | 56 } | 
|  | 57 | 
|  | 58 int64_t GetSystemTime() { | 
|  | 59 	assert(sizeof(int64_t) >= sizeof(time_t)); | 
|  | 60 	time_t t = std::time(nullptr); | 
|  | 61 	return *reinterpret_cast<int64_t*>(&t); | 
|  | 62 } | 
|  | 63 | 
|  | 64 } |