一、获取时间
function toTwo(n){ return n<10 ? '0'+n :''+n; } function getTime(){ var objDate=new Date(); //date=>object //number var year=objDate.getFullYear(); var mothn=objDate.getMonth(); var date=objDate.getDate(); var week=objDate.getDay(); var hours=objDate.getHours(); var minu=objDate.getMinutes(); var sec=objDate.getSeconds(); mothn=mothn+1; switch (week) { case 0: week="星期天" case 1: week="星期一" case 2: week="星期二" case 3: week="星期三" case 4: week="星期四" case 5: week="星期五" case 6: week="星期六" } var str=year+"年"+mothn+"月"+date+"日 "+week+" "+toTwo(hours)+"时"+toTwo(minu)+"分"+toTwo(sec)+"秒"; document.body.innerHTML=str; } setInterval(getTime,1000); getTime();
二、倒计时
function timeDown() { var timer=null; //new Date(2015, 3, 6, 0, 0, 0) 月份从0开始,即3表示4月份 var iNow=new Date(); var iNew=new Date(2015, 3, 5, 22, 23,0); var ts = iNew-iNow; var dd = parseInt(ts / 1000 / 60 / 60 / 24, 10); var hh = parseInt(ts / 1000 / 60 / 60 % 24, 10); var mm = parseInt(ts / 1000 / 60 % 60, 10); var ss = parseInt(ts / 1000 % 60, 10); dd = checkTime(dd); hh = checkTime(hh); mm = checkTime(mm); ss = checkTime(ss); var str= dd + "天" + hh + "时" + mm + "分" + ss + "秒"; document.body.innerHTML=str; if(iNow.toString()==iNew.toString()) { clearInterval(timer); } } function checkTime(n){ return n<10 ? '0'+n :''+n; } var timer=setInterval(timeDown,1000); timeDown();