59 lines
1.4 KiB
C++
59 lines
1.4 KiB
C++
#include <system_error>
|
|
|
|
#include "timeutils.h"
|
|
|
|
time_t current_time() {
|
|
struct timespec tp;
|
|
|
|
if (clock_gettime(CLOCK_REALTIME, &tp)) {
|
|
throw std::system_error(errno, std::generic_category(), "clock_gettime()");
|
|
}
|
|
|
|
return tp.tv_sec;
|
|
}
|
|
|
|
std::string short_time(time_t time) {
|
|
struct tm tm;
|
|
gmtime_r(&time, &tm);
|
|
|
|
char buf[16];
|
|
size_t len = strftime(buf, 16, "%Y-%m-%d", &tm);
|
|
return std::string(buf, len);
|
|
}
|
|
|
|
std::string full_time(time_t time) {
|
|
struct tm tm;
|
|
gmtime_r(&time, &tm);
|
|
|
|
char buf[32];
|
|
size_t len = strftime(buf, 32, "%Y-%m-%d %H:%M:%S GMT", &tm);
|
|
return std::string(buf, len);
|
|
}
|
|
|
|
std::string to_rfc3339(time_t time) {
|
|
struct tm tm;
|
|
gmtime_r(&time, &tm);
|
|
|
|
char buf[32];
|
|
size_t len = strftime(buf, 32, "%Y-%m-%dT%H:%M:%SZ", &tm);
|
|
return std::string(buf, len);
|
|
}
|
|
|
|
std::string relative_time(time_t from, time_t to) {
|
|
time_t diff = to - from;
|
|
|
|
if (diff < 60) {
|
|
return std::to_string(diff) + 's';
|
|
} else if (diff < 60 * 60) {
|
|
return std::to_string(diff / 60) + 'm';
|
|
} else if (diff < 24 * 60 * 60) {
|
|
return std::to_string(diff / (60 * 60)) + 'h';
|
|
} else if (diff < 7 * 24 * 60 * 60) {
|
|
return std::to_string(diff / (24 * 60 * 60)) + 'd';
|
|
} else if (diff < 4 * 7 * 24 * 60 * 60) {
|
|
return std::to_string(diff / (7 * 24 * 60 * 60)) + 'w';
|
|
} else {
|
|
return short_time(from);
|
|
}
|
|
}
|