]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
lib/timeutils: add strtime_short()
authorKarel Zak <kzak@redhat.com>
Tue, 24 May 2016 11:21:26 +0000 (13:21 +0200)
committerKarel Zak <kzak@redhat.com>
Tue, 24 May 2016 11:21:26 +0000 (13:21 +0200)
Signed-off-by: Karel Zak <kzak@redhat.com>
include/timeutils.h
lib/timeutils.c

index 2ec193a094ab4f031d466b5d81a2dc019dae0988..265577f5e21761a1eab6576d321a6a8fdc42853d 100644 (file)
@@ -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 */
index fdf0024edb6bc8d76ae1cfcc647e74d704d744de..25a163e41ffcc47f945d0c521e3884b04df932d8 100644 (file)
@@ -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