要获取两个时间戳之间的时差,请尝试运行以下代码。在这里,我们正在计算两个时间戳之间的小时,分钟和秒的总数-
<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; //获取两个日期之间的总天数 var days = Math.floor(res / 86400); document.write("<br>Difference (Days): "+days); //上班时间 var hours = Math.floor(res / 3600) % 24; document.write("<br>Difference (Hours): "+hours); //得到分钟 var minutes = Math.floor(res / 60) % 60; document.write("<br>Difference (Minutes): "+minutes); //得到秒 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