Frantisek
Frantisek

Reputation: 7703

Javascript for "how many seconds have passed since this timestamp"

Is there a Javascript equivalent for this PHP code?

function secondsAgo($unixtime){
   return time() - $unixtime;
}

Example usage:

echo secondsAgo(time()-10); // 10

I have a unixtimestamp in Javascript and need to find out how many seconds have passed from today until that timestamp.

Upvotes: 0

Views: 1969

Answers (2)

Marc B
Marc B

Reputation: 360872

JS timestamps are the same as Unix/PHP timestamps, time since Jan 1/1970, except JS uses milliseconds instead.

var msts = new Date().getTime(); // timestamps in millisecs;
var ts = msts / 1000; // now directly compariable to PHP timestamp.

var phpts = <?php echo json_encode(time()); ?>;

var diff = phpts - ts; // difference in seconds.

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 78046

JS equivelant:

function secondsAgo(unixTime) {
    return Math.round((new Date().getTime() / 1000)) - unixTime;
}

Upvotes: 3

Related Questions