1

I am trying to show the least minimum time segment based on a unix timestamp.

Example:

  1. "50 seconds ago" needs to be 50s.
  2. "65 seconds ago" needs to be 1m because its more 60 seconds is in minutes.
  3. "65 minutes ago" needs to be 1h because its more 60 minutes is in minutes.
  4. "25 hours ago" => 1d.
  5. "8 days ago" => 1w.
  6. ... 1mon (for months).
  7. ... 2y (for years).

I have tried a few libraries like moment i.e.

moment.unix(1440187622).fromNow()

but that returns a "sentence", however its not exactly what I want.

Any ideas?

skay-
  • 1,546
  • 3
  • 16
  • 26
  • http://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site – adeneo Oct 08 '16 at 20:58
  • Not everyone likes "friendly" formats. Seeing 4 items with "yesterday" does not help to determine when they occurred relative to each other. :-) – RobG Oct 08 '16 at 21:24
  • You can do it yourself with about 12 lines of code. Did you try? – jcaron Oct 08 '16 at 22:23
  • @RobG Maybe, but in this case that's what I want to show. – skay- Oct 08 '16 at 23:07
  • @jcaron I gave it a quick try but I wanted to see some other opinions as well. – skay- Oct 08 '16 at 23:08

1 Answers1

0

Did you have a look at moment.js durations? You could write a function like this:

function segment(duration) {
  return duration.years() > 0 ? duration.years() + 'y' :
    duration.months() > 0 ? duration.months() + 'mon' :
    // ...
    duration.seconds() > 0 ? duration.seconds() + 's' : '';
}
segment(moment.duration(moment.diff(moment(),moment.unix(1440187622))))
Christian Zosel
  • 1,424
  • 1
  • 9
  • 16