Question

i get the time through a json, like this

"timeAddedToDrive": 1398813844020

Im wondering if i can create a jQuery or JS that begun a count from that time, so users can see how much time passed since the event happened in seconds like

event was 48:05 minutes ago...

Its that posible?

PD: apologies about my english, i know its pretty bad

Was it helpful?

Solution

I recommend that you use the library moment.js.

You can use this library to convert date values from various storage formats into others including human-readable descriptions like you are looking for.

The function .fromNow() is close to what you are looking for but it is probably not precise enough. With a little bit more effort you can use moment.js to determine the diff of timestamp relative to now, convert that to duration and then get the minutes and seconds from the duration.

var timeAddedToDrive = 1398813844020;

var now = moment();
var timePassed = now.diff(timeAddedToDrive);

// fromNow function works but is not precise
alert( moment(timeAddedToDrive).fromNow());

// for more precision we'll get the minutes and seconds from the DURATION
var seconds = moment.duration(timePassed).seconds(); 
var minutes = moment.duration(timePassed).minutes(); 
var output = "event was " +
    minutes.toString() + ":" + 
    seconds.toString() + " minutes ago"

alert( output );

Here's a jsFiddle that shows both approaches: jsFiddle

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top