js 獲取當前時間並且進行增加或者刪減相對應的天數

首先是寫一個函數,傳入相對應的天數,0 是今天, 正數是要增加的天數,負數是要刪減的天數

​
        // 封裝時間函數
        getDay(day){
          var today = new Date();
          var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
          today.setTime(targetday_milliseconds); //注意,這行是關鍵代碼
          var tYear = today.getFullYear();
          var tMonth = today.getMonth();
          var tDate = today.getDate();
          tMonth = this.doHandleMonth(tMonth + 1);
          tDate = this.doHandleMonth(tDate);
          return tYear+"-"+tMonth+"-"+tDate;
        },
        doHandleMonth(month){
          var m = month;
          if(month.toString().length == 1){
            m = "0" + month;
          }
          return m;
        },

​

說說這些代碼的使用:

獲取當前時間日期:this.getDay(0)

在當前時間減掉8天:this.getDay(-8)

在當前時間加上5天:this.getDay(5)

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章