獲取當前時間的前後幾天的日期,前後幾個月的日期,前後幾年的日期

獲取當前時間的前後幾天的日期

function GetDay(day) {
    var time = new Date();
    time.setDate(time.getDate() + day);//獲取Day天后的日期 
    var y = time.getFullYear();
    var m = time.getMonth() + 1;//獲取當前月份的日期 
    var d = time.getDate();
    if (m < 10) {
      m = "0" + m;
    }
    if (d < 10) {
        d = '0' + d;
    }
    return y + "-" + m + "-" + d;
  }

參數day爲正數則往後推 反之往前推
調用:GetDay(7)或者GetDay(-7)

前後幾個月的日期,前後幾年的日期

month爲正數則往後推 反之往前推
type區分返回的數據格式 1返回年,月 2返回年

  function GetMonth(month,type) {
    var time = new Date();
    time.setMonth(time.getMonth() + month);//設置month月後的時間
    var y = time.getFullYear();
    var m = time.getMonth() + 1;//獲取當前月份
    var d = time.getDate();
    if (m < 10) {
      m = "0" + m;
    }
    if (d < 10) {
        d = '0' + d;
    }
    if(type == 1){
      return y + "-" + m;
    }else if(type == 2){
      return y;
    }
  }

GetMonth(2,1)或者GetMonth(-2,1)//返回年-月

GetMonth(2,2)或者GetMonth(-2,2)//返回年

獲取當前的時間
type區分返回的數據格式 1返回年-月-日 2返回年-月 3返回年

function NewData(type){
    var timestamp = Date.parse(new Date());
    var date = new Date(timestamp);
    //獲取年份  
    var Y =date.getFullYear();
    //獲取月份  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //獲取當日日期 
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); 
    if(type == 1){
        return  Y + '-'  + M+ '-' + D;
    }else if(type == 2){
        return  Y + '-'  + M; 
    }else if(type == 3){
        return  Y; 
    }
    
}

NewData(1)//返回格式 年-月-日
NewData(2)//返回格式 年-月
NewData(3)//返回格式 年

發佈了34 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章