How to get time difference between two timestamps in seconds?

To get the time difference between two timestamps, try to run the following code. Here, we are calculating the total number of hours, minutes and seconds between two timestamps ?

Example

<html>
   <head>
      <title>JavaScript Dates</title>
   </head>
   <body>
      <script>
          var date1, date2;

          date1 = new Date( "Jan 1, 2018 11:10:05" );
          document.write(""+date1);

          date2 = new Date( "Jan 1, 2018 08:15:10" );
          document.write("&lt;br&gt;"+date2);

          var res = Math.abs(date1 - date2) / 1000;
          
          // get total days between two dates
          var days = Math.floor(res / 86400);
          document.write("&lt;br&gt;Difference (Days): "+days);
          
          // get hours
          var hours = Math.floor(res / 3600) % 24;
          document.write("&lt;br&gt;Difference (Hours): "+hours);
          
          // get minutes
          var minutes = Math.floor(res / 60) % 60;
          document.write("&lt;br&gt;Difference (Minutes): "+minutes);

          // get seconds
          var seconds = res % 60;
          document.write("&lt;br&gt;Difference (Seconds): "+seconds);
      </script>
   </body>
</html>

Output

Mon Jan 01 2018 11:10:05 GMT+0530 (India Standard Time)
Mon Jan 01 2018 08:15:10 GMT+0530 (India Standard Time)
Difference (Days): 0
Difference (Hours): 2
Difference (Minutes): 54
Difference (Seconds): 55
Updated on: 2020-06-18T12:28:48+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements