<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <div id="div1"> </div> <script type="text/javascript"> var oDiv = document.getElementById("div1"); var str = getTime(); oDiv.innerHTML+=str; function getTime(){ var tarTime = new Date("2017/04/5 21:59:59"); var nowTime = new Date(); var tarSpan = tarTime.getTime(); var nowSpan = nowTime.getTime(); // var diffTime = tarSpan - nowSpan; // 1、算出总毫秒差中包含的小时有几个 var hour = Math.floor(diffTime/(1000*60*60)); // 2、当前这几个小时占了多少毫秒 var hourMs = hour*60*60*1000; // 3、接下来算分钟的时候,需要把小时占用的减去 var spanMs = diffTime -hourMs; // 4、开始算spanMs中包含多少分钟 var minute=Math.floor(spanMs/(1000*60)); // 5、算这么多分钟占用多少毫秒 var minuteMs=minute*60*1000; // 6、算秒的时候把分钟占用的也减去 spanMs=spanMs-minuteMs; // 7、算剩下的包含多少秒 var second = Math.floor(spanMs/1000); return zero(hour)+":"+zero(minute)+":"+zero(second); } function zero(value){ return value < 10?"0"+value:value; } </script> </body> </html>
时间: 2024-10-21 22:19:45