Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...