Javascript Data Type How to - Get the time difference between 2 dates








Question

We would like to know how to get the time difference between 2 dates.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-2.0.2.js'></script>
<script type='text/javascript'>
<!--from w w  w  . j  ava  2s .  c  o  m-->
Number.prototype.format = function(){
    return [
        (this/86400|0), "days",
        (this/3600|0) % 24 , "hours",
        (this/60|0) % 60 , "minutes",
        (this|0) % 60 , "seconds"
    ].join(" ");
};
var date1 = new Date("2014-12-25 12:23:56"),
    date2 = new Date("2013-12-25 11:20:21");
$("body").append(((date1 - date2)/1000|0).format());

</script>
</head>
<body>Difference:
</body>
</html>

The code above is rendered as follows: