1 <script> 2 function getTime() { 3 var endTime=new Date('2017/04/25 00:00:00'); 4 var nowTime=new Date(); 5 var t=endTime-nowTime; 6 var t1=Math.abs(t); 7 var t2=t1 / 1000/ 60/60; 8 var result=t2.toFixed(2); 9 return result; 10 } 11 document.body.innerHTML='距离今天结束还有'+getTime()+'小时'; 12 </script>
1 <body> 2 <div id="testDiv" data-time="2017/04/25 00:00:00"> 3 <span class="detail"><b>07</b>天<b>09</b>时<b>16</b>分<b>05</b>秒</span> 4 </div> 5 <script> 6 var str = document.getElementById('testDiv').getAttribute('data-time'); 7 var terminalTime = new Date(str); 8 var bArr = document.getElementsByTagName('b'); 9 downCount(); 10 function downCount() { 11 var nowDate = new Date(); 12 var chaZhi = terminalTime - nowDate; 13 if(chaZhi < 0) { 14 clearTimeout(setIntervalId) 15 } 16 var myDate = setTime(chaZhi); 17 bArr[0].innerHTML = myDate.date; 18 bArr[1].innerHTML = myDate.hours; 19 bArr[2].innerHTML = myDate.minutes; 20 bArr[3].innerHTML = myDate.seconds; 21 } 22 var setIntervalId = setInterval(downCount, 1000); 23 24 var date=new Date(); 25 var date2=new Date(); 26 date2.setHours(date2.getHours()+2); 27 console.log('date2'+date2); 28 function setTime(time) {//time是给一个时间差 29 var date = new Date(); 30 date.date = Math.floor(time / (1000 * 60 * 60 * 24)); 31 date.hours = Math.floor(( time / (1000 * 60 * 60)) % 24); 32 date.minutes = Math.floor(( time / (1000 * 60)) % 60); 33 date.seconds = Math.floor(( time / 1000) % 60); 34 date.milliseconds = Math.floor(time % 1000); 35 return date; 36 } 37 38 var date1=new Date(); 39 var date2=new Date(); 40 date2.setHours(date2.getHours()+2); 41 console.log('date2'+date2); 42 </script> 43 </body>