如何獲取兩個時間戳之間的時差(秒)?


若要獲取兩個時間戳之間的時差,請嘗試執行以下程式碼。此處,我們計算兩個時間戳之間的總小時數、分鐘數和秒數 −

示例

線上演示

<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("<br>"+date2);

         var res = Math.abs(date1 - date2) / 1000;
         
         // get total days between two dates
         var days = Math.floor(res / 86400);
         document.write("<br>Difference (Days): "+days);                        
         
         // get hours        
         var hours = Math.floor(res / 3600) % 24;        
         document.write("<br>Difference (Hours): "+hours);  
         
         // get minutes
         var minutes = Math.floor(res / 60) % 60;
         document.write("<br>Difference (Minutes): "+minutes);  
     
         // get seconds
         var seconds = res % 60;
         document.write("<br>Difference (Seconds): "+seconds);  
      </script>
   </body>
</html>

輸出

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

更新時間: 18-Jun-2020

2 千+ 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告