<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>我的倒數計時</title> </head> <body> <h2>當前時間:</h2> <p id="thisTime"></p> <h2>距離2016/09/10 10:00還有:</h2> <p id="countDown"><p/> <script type="text/javascript"> window.onload = function () {//在dom文件樹載入完和所有檔案載入完之後執行一個函式 timer({ currentTime: true, objId: 'thisTime' }); timer({ objId: 'countDown', endtime: "2016/9/1,18:00" }) }; function timer(a) { if (a.currentTime) { var now = new Date(); var year = now.getFullYear();//返回年份(4位數字) var month = now.getMonth() + 1;//返回月份(0-11,所以+1) var day = now.getDate();//返回某天(1-31) var h = now.getHours();//返回小時(0-23) var m = now.getMinutes();//返回分鐘(0-59) var s = now.getSeconds();//返回秒數(0-59) //補O m = m < 10 ? '0' + m : m; s = s < 10 ? '0' + s : s; var weekday = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; document.getElementById(a.objId).innerHTML = year + '年' + month + '月' + day + '日' + weekday[now.getDay()] + ' ' + h + ':' + m + ':' + s; setTimeout(function () { timer(a) }, 1000); } else { var endtime = new Date(a.endtime);//結束時間 var nowtime = new Date();//當前時間 var lefttime = parseInt((endtime.getTime() - nowtime.getTime()) / 1000); //計算差的秒數 //一天24小時 一小時60分鐘 一分鐘60秒 d = parseInt(lefttime / 3600 / 24); h = parseInt((lefttime / 3600) % 24); m = parseInt((lefttime / 60) % 60); s = parseInt(lefttime % 60); document.getElementById(a.objId).innerHTML = d + "天" + h + "小時" + m + "分" + s + "秒"; if (lefttime > 0) { setTimeout(function () { timer(a) }, 1000); } } } </script> </body> </html>
執行效果: