0xPingo
0xPingo

Reputation: 2197

Moment.js - time elapsed with local timezone and UNIX input

I am working with an API that returns dates in UNIX format: i.e. 1441647410.

With the following moment.js helper, I am able to convert it to a more readable format (05/22/15, 09:33):

UI.registerHelper('formatUnix', function(context, options) {
  if(context)
    return moment.unix(context).format('MM/DD/YY, hh:mm');
});

Instead of displaying an absolute time, I'd like to display time elapsed from now (i.e. 5 hrs ago, or 11 weeks ago) in this example. How could I do that? I am trying to define now with moment(), but it doesn't seem to be working:

UI.registerHelper('fromNow', function(context, options) {
  if(context)
    var now = moment();
    var diff = now - context;
    return moment.unix(diff).format('hh');
});

How can I should an amount of time elapsed from now (11 weeks ago) instead of an absolute time (5/22/15)? Also, is there any way for the browser to automatically grab the client's local time?

Thanks !

Upvotes: 2

Views: 1036

Answers (2)

GregL
GregL

Reputation: 38103

You were close, you just need to use the fromNow() method after constructing the moment instance using moment.unix():

moment.unix(context).fromNow()

Upvotes: 1

kravits88
kravits88

Reputation: 13049

What about parsing unix into moment time and then using from:

return moment(context).from(moment());

Upvotes: 2

Related Questions