From: Karel Zak Date: Tue, 24 May 2016 11:21:26 +0000 (+0200) Subject: lib/timeutils: add strtime_short() X-Git-Tag: v2.29-rc1~229 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=eee665bb5a4fb648d29d9f2fafb0490d46617053;p=thirdparty%2Futil-linux.git lib/timeutils: add strtime_short() Signed-off-by: Karel Zak --- diff --git a/include/timeutils.h b/include/timeutils.h index 2ec193a094..265577f5e2 100644 --- a/include/timeutils.h +++ b/include/timeutils.h @@ -70,4 +70,11 @@ int strtimeval_iso(struct timeval *tv, int flags, char *buf, size_t bufsz); int strtm_iso(struct tm *tm, int flags, char *buf, size_t bufsz); int strtime_iso(const time_t *t, int flags, char *buf, size_t bufsz); +#define UL_SHORTTIME_THISYEAR_HHMM (1 << 1) + +int time_is_today(const time_t *t, struct timeval *now); +int time_is_thisyear(const time_t *t, struct timeval *now); + +int strtime_short(const time_t *t, struct timeval *now, int flags, char *buf, size_t bufsz); + #endif /* UTIL_LINUX_TIME_UTIL_H */ diff --git a/lib/timeutils.c b/lib/timeutils.c index fdf0024edb..25a163e41f 100644 --- a/lib/timeutils.c +++ b/lib/timeutils.c @@ -413,6 +413,44 @@ int strtime_iso(const time_t *t, int flags, char *buf, size_t bufsz) return format_iso_time(&tm, 0, flags, buf, bufsz); } +/* relative time functions */ +int time_is_today(const time_t *t, struct timeval *now) +{ + if (now->tv_sec == 0) + gettimeofday(now, NULL); + return *t / (3600 * 24) == now->tv_sec / (3600 * 24); +} + +int time_is_thisyear(const time_t *t, struct timeval *now) +{ + if (now->tv_sec == 0) + gettimeofday(now, NULL); + return *t / (3600 * 24 * 365) == now->tv_sec / (3600 * 24 * 365); +} + +int strtime_short(const time_t *t, struct timeval *now, int flags, char *buf, size_t bufsz) +{ + struct tm tm; + int rc = 0; + + localtime_r(t, &tm); + + if (time_is_today(t, now)) { + rc = snprintf(buf, bufsz, "%02d:%02d", tm.tm_hour, tm.tm_min); + if (rc < 0 || (size_t) rc > bufsz) + return -1; + rc = 1; + + } else if (time_is_thisyear(t, now)) { + if (flags & UL_SHORTTIME_THISYEAR_HHMM) + rc = strftime(buf, bufsz, "%b%d/%H:%M", &tm); + else + rc = strftime(buf, bufsz, "%b%d", &tm); + } else + rc = strftime(buf, bufsz, "%Y-%b%d", &tm); + + return rc <= 0 ? -1 : 0; +} #ifdef TEST_PROGRAM_TIMEUTILS