Js獲取最近當日、昨天、近一周、近一月的時間


首先定義兩個方法,相當於進行了封裝

 /**
       * 
       * @param dateNow :Date類
       * @param intervalDays :間隔天數
       * @param bolPastTime  :Boolean,判斷在參數date之前,還是之后,
       */
     function getDateRange(dateNow,intervalDays,bolPastTime){
        let oneDayTime = 24 * 60 * 60 * 1000;
        let list = [];
        let lastDay;
 
        if(bolPastTime == true){
            lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
            list.push(this.formateDate(lastDay));
            list.push(this.formateDate(dateNow));
        }else{
            lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
            list.push(this.formateDate(dateNow));
            list.push(this.formateDate(lastDay));
        }
        return list;
     }
     function formateDate(time){
        let year = time.getFullYear()
        let month = time.getMonth() + 1
        let day = time.getDate()
 
        if (month < 10) {
          month = '0' + month
        }
 
        if (day < 10) {
          day = '0' + day
        }
 
        return year + '-' + month + '-' + day + ''
 
     }

  

具體獲取數據如下:(調用上面方法即可)

//獲取當前日期(2020-03-24)
     var date = new Date();
     var list = this.getDateRange(date,6,true)
     console.log("獲取近一周日期范圍:\n開始日期:"+list[0]+";\n結束日期:"+list[1]);

     var list = this.getDateRange(date,30,true)
     console.log("獲取近一個月日期范圍:\n開始日期:"+list[0]+";\n結束日期:"+list[1]);

     var list = this.getDateRange(date,0,true)
     console.log("獲取今天日期范圍:\n開始日期:"+list[0]+";\n結束日期:"+list[1]);

     var list = this.getDateRange(date,1,true)
     console.log("獲取昨天日期范圍:\n開始日期:"+list[0]+";\n結束日期:"+list[0]);

     var list = this.getDateRange(date,6,false)
     console.log("獲取下一周日期范圍:\n開始日期:"+list[0]+";\n結束日期:"+list[1]);

     var list = this.getDateRange(date,30,false)
     console.log("獲取下一個月日期范圍:\n開始日期:"+list[0]+";\n結束日期:"+list[1]);

  具體打印結果還請親自動手測試;

參考原文:https://blog.csdn.net/qq_41090476/article/details/96133830


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM