Sorceress

Untitled

Aug 8th, 2014
497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.78 KB | None | 0 0
  1. static char *strdelta(int delta, char *buf, int compact) {
  2.   *buf = '\0';
  3.   const char *tail = delta < 0 ? "ago" : "from now";
  4.   struct { const char *fmt; int div; } tab[] = {
  5.     { "%d day%s ", 86400 },
  6.     { "%d hour%s ", 3600 },
  7.     { "%d minute%s ", 60 },
  8.     { "%d second%s ", 1 },
  9.     { NULL, 0 }
  10.   };
  11.   int i;
  12.   delta = abs(delta);
  13.   int sigfigs = 0;
  14.   for (i = 0; tab[i].fmt; i++) {
  15.     int res = (i > 0 ? (delta % tab[i - 1].div) : delta) / tab[i].div;
  16.     if (res == 0 && sigfigs == 0) continue;
  17.     sigfigs++;
  18.     if (delta >= tab[i].div && sigfigs < 2) {
  19.       sprintf(buf + strlen(buf), tab[i].fmt, res, res != 1 ? "s" : "");
  20.       if (compact) break;
  21.     }
  22.   }
  23.   if (*buf) {
  24.     strcat(buf, tail);
  25.   } else {
  26.     strcpy(buf, "now");
  27.   }
  28.   return buf;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment