Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 421
jeff Avatar asked Feb 02 '14 21:02

jeff


People also ask

How do you find the time difference between two timestamps in seconds?

If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.

How do you find the difference between two times in a moment?

To get the hour difference between two times with moment. js, we can use the duration , diff , asHours and asMinutes methods. For instance, we can write: const startTime = moment("12:26:59 am", "HH:mm:ss a"); const endTime = moment("06:12:07 pm", "HH:mm:ss a"); const duration = moment.


1 Answers

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());
 });

like image 116
CodeToad Avatar answered Sep 18 '22 18:09

CodeToad