How to get time difference between two timestamps in seconds with jQuery?

jeff picture jeff · Feb 2, 2014 · Viewed 56.1k times · Source

I want to display x seconds ago based on a MySQL Timestamp.

I found the plugin called timeago

But I cannot find a way to make it display only seconds.

I'm OK with 61 seconds, or 300 seconds. Any way to convert the output to seconds with timeago, or with pure jQuery / JavaScript ?

Thanks for any help !

Edit:

Sample Case :

$time1 = "2014-02-02 23:54:04"; // plus PHP ways to format it.
//$time2 = NOW() , or date(); whatever. 

I just want to get how many seconds since $time1.

Edit 2:

Working code :

<script type="text/javascript">
$(function(){
    var d2 = new Date();
    var d1 = new Date("2014-02-02 23:54:04");
    $("a#timedif").html("Diff. Seconds : "+((d2-d1)/100).toString());
    // note that you may want to round the value
});
</script>

It outputs Diff. Seconds : NaN

Answer

CodeToad picture CodeToad · Feb 2, 2014

assuming you parse the string into JavaScript date object, you can do (date2 - date1)/1000

to parse mysql format timestamp, just feed the string into new Date():

 var d2 = new Date('2038-01-19 03:14:07');
 var d1 = new Date('2038-01-19 03:10:07');

 var seconds =  (d2- d1)/1000;

fix of edit 2 in the question:

<script type="text/javascript">
$(function(){
var d2 = new Date();
var d1 = new Date("2014-02-02 23:54:04");
$("a#timedif").html("Diff. Seconds : "+((d2-d1)/1000).toString());
 });