關於時間和倒計時等問題
阿新 • • 發佈:2018-12-30
//倒計時 window.onload=function(){ var curtime = new Date(); var endtime = new Date('2018,12,20') var lefttime = Math.ceil((endtime.getTime() - curtime.getTime())/(24*60*60*1000)); document.getElementById('timeShow').innerHTML = lefttime; } //當前時間 window.onload=function(){ clock(); } function checkTime(i){ if(i<10){ i='0'+i } return i; } function clock(){ var myDate = new Date(); var year = myDate.getFullYear(); var month = myDate.getMonth()+1; var date = myDate.getDate(); var weekday = new Array(7) weekday[0]='星期日' weekday[1]='星期一' weekday[2]='星期二' weekday[3]='星期三' weekday[4]='星期四' weekday[5]='星期五' weekday[6]='星期六' var d = myDate.getDay(); var hour = myDate.getHours(); var minute = myDate.getMinutes(); var second = myDate.getSeconds(); minute = checkTime(minute); second = checkTime(second); document.getElementById('show').innerHTML = year+'年'+month+'月'+date+'日'+weekday[d]+hour+':'+minute+':'+second; setInterval('clock()',100); } //限時搶購 window.onload=function(){ var timer = setInterval(clock,50); } function clock(){ var curtime = new Date(); var endtime = new Date('2018/12/15,17:03:00'); var lefttime = parseInt((endtime.getTime() - curtime.getTime())/1000); var d = parseInt(lefttime/(24*60*60)); var h = parseInt(lefttime/(60*60)%24); var m = parseInt(lefttime/60%60); var s = lefttime%60; document.getElementById('LeftTime').innerHTML = d+'天'+h+'時'+m+'分'+s+'秒'; if(lefttime <=0){ document.getElementById('LeftTime').innerHTML ='搶購結束'; clearInterval(timer); } }
Date() 返回當前日期和時間
getDate() 檢視Date物件並返回時期(1-31)
getDay() 返回星期幾(0-6)
getSeconds() 返回秒數
getTime() 返回毫秒數
getYear() 返回年份 例:2018 ---118 2009 ---109
getFullYear() 返回完整格式年數 2018
想要獲取星期幾的時候,最好寫一個數組,然後陣列呼叫方法。
封裝一個函式,當值<10時,在他前面加一個0.
%取模 求餘數的意思。
var h = parseInt(lefttime/(60*60)%24); lefttime/(60*60)還剩多少小時,%24 表示去掉天數還剩幾小時
var m = parseInt(lefttime/60%60); lefttime/60 還剩多少分鐘, %60 去掉小時還剩多少分鐘
setInterval(clock,50) 此處clock表示呼叫clock函式
setInterval('clock()',50) 此處'clock ()'表示 一段字串格式的js程式碼