Js日期加減(天數),時間加減,日期運算,可直接調用


根據傳入的日期做加減法計算,整數為加法,負數為減法,但是是天。

 num可傳入: 1,2,3,-1,-2,-3等,默認是加一天;date可傳入: 2017-01-01格式的,不傳的話默認是當天日期。

 

function dateChange(num = 1,date = false) {
  if (!date) {
    date = new Date();//沒有傳入值時,默認是當前日期
    date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
  }
  date += " 00:00:00";//設置為當天凌晨12點
  date = Date.parse(new Date(date))/1000;//轉換為時間戳
  date += (86400) * num;//修改后的時間戳
  var newDate = new Date(parseInt(date) * 1000);//轉換為時間
  return newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate();
}

調用結果:

1、dateChange();

  結果:

    

2、dateChange(30);

  結果:

    

3、dateChange(-10);

  結果:

    

4、dateChange(3, '2018-02-27');

  結果:

    

5、dateChange(-2, '2016-3-1');

  結果:

    

 


免責聲明!

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



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