coyote/timeutils.cpp

73 lines
1.9 KiB
C++
Raw Normal View History

#include <cstring>
2023-11-23 06:05:17 +00:00
#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);
}
static const char* day_names[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
static const char* month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
std::string to_web_date(time_t time) {
struct tm tm;
gmtime_r(&time, &tm);
char buf[32];
size_t len = strftime(buf, 32, "XXX, %d XXX %Y %H:%M:%S GMT", &tm);
memcpy(buf, day_names[tm.tm_wday], 3);
memcpy(buf + 3 + 2 + 2 + 1, month_names[tm.tm_mon], 3);
return std::string(buf, len);
}
2023-11-23 06:05:17 +00:00
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';
2023-11-23 08:49:27 +00:00
} else if (diff < 24 * 60 * 60) {
2023-11-23 06:05:17 +00:00
return std::to_string(diff / (60 * 60)) + 'h';
2023-11-23 08:49:27 +00:00
} else if (diff < 7 * 24 * 60 * 60) {
2023-11-23 06:05:17 +00:00
return std::to_string(diff / (24 * 60 * 60)) + 'd';
2023-11-23 08:49:27 +00:00
} else if (diff < 4 * 7 * 24 * 60 * 60) {
return std::to_string(diff / (7 * 24 * 60 * 60)) + 'w';
2023-11-23 06:05:17 +00:00
} else {
return short_time(from);
}
}