1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>倒计时原理</title>
6 <script type="text/javascript">
7 window.onload = function(){
8 var oP = document.getElementsByTagName('p')[0];
9 //var now = new Date();//Wed Apr 12 2017 16:21:09 GMT+0800 (中国标准时间)
10 //console.log(now);
11 //var setTime = new Date(2017,3,12,16,23,0);//Wed Apr 12 2017 16:23:00 GMT+0800 (中国标准时间)
12 //注:时间中的月份是从数字0开始计数的,因此此例中2017,3,12代表Apr 12 2017
13 //console.log(setTime);
14
15 /*
16 var now = new Date();
17 var setTime = new Date('May 12 2017 16:21:00');
18 */
19
20 //console.log(setTime-now);//21080846532,返回毫秒数
21 //console.log((setTime-now)/1000);//21080846.532,毫秒转化成秒
22 //console.log(Math.floor((setTime-now)/1000));//去除小数点后的数值
23
24 /*
25 var t = Math.floor((setTime-now)/1000);
26
27 var str = Math.floor(t/86400) + '天' + Math.floor(t%86400/3600) + '时' + Math.floor(t%86400%3600/60) + '分' + t%60 + '秒';
28
29 console.log(str);
30
31 */
32 //天:Math.floor(t/86400)
33 //时:Math.floor(t%86400/3600)
34 //分:Math.floor(t%86400%3600/60)
35 //秒:t%60
36
37
38 // 数字形式:new Date( 2013,4,1,9,48,12 );
39 // 字符串形式:new Date('June 10,2013 12:12:12');
40
41 //封装:
42 oP.innerHTML = countdown();
43 setInterval(function(){
44 oP.innerHTML = countdown();
45 },1000)
46 function countdown(){
47 var now = new Date();
48 var setTime = new Date('May 12 2017 16:21:00');
49 var t = Math.floor((setTime-now)/1000);
50 var str = Math.floor(t/86400) + '天' + Math.floor(t%86400/3600) + '时' + Math.floor(t%86400%3600/60) + '分' + t%60 + '秒';
51 return str;
52 }
53 };
54 </script>
55 </head>
56 <body>
57 <p></p>
58 </body>
59 </html>