1、頁面排版
<button onclick="before()">上一天</button> <button onclick="after()">下一天</button> <div id="date"> </div>
2、先實例化Date
var date=new Date();
3、寫入頁面
var el=document.getElementById('date')//找到元素id el.innerHTML=myGetDate()//渲染頁面 //這里是用函數封裝的,方便后面使用 function myGetDate(){ return `${date.getFullYear()}年${date.getMonth()+1}月${date.getDate()}日` }
4、計算上一天
function before(){ date=new Date();//每次調用重新實例化Date date.setTime(date.getTime()-(1000*60*60*24))//獲取時間戳到當前時間的毫秒數減去一天時間的毫秒數 el.innerHTML=myGetDate()//調用上面寫的排版函數,渲染頁面 }
5、計算下一天
function after(){ date=new Date(); date.setTime(date.getTime()+(1000*60*60*24)) el.innerHTML=myGetDate() }
下一天計算與上一天同理,只需把減改成加就可以了