js日期操作

获取本周第一天

function getFirstDayOfWeek (date) {
    var day = date.getDay() || 7;
    return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1 - day);
};

日期相加

 addDate (date, days) {
      if (days == undefined || days == '') {
        days = 1
      }
      var date = new Date(date)
      date.setDate(date.getDate() + days)
      var month = date.getMonth() + 1
      var day = date.getDate()
      if (month < 10) month = '0' + month
      if (day < 10) day = '0' + day
      return date.getFullYear() + '-' + month + '-' + day
 },

日期相减

DateMinus(date1,date2) {
    var start = date1.replace(/-/g,'/')
    var end = date2.replace(/-/g,'/')
    var sdate = new Date(start)
    var now = new Date(end)
    var days = now.getTime() - sdate.getTime()
    var day = parseInt(days / (1000 * 60 * 60 * 24))
    console.log(day)
}

格式化日期

formatDate (dateTime) {
      let time = new Date(dateTime)
      let year = time.getFullYear()
      let month = time.getMonth() + 1
      if (month < 10)  month = '0' + month
      let day = time.getDate()
      if (day < 10)  day = '0' + day
      let returnDate = year + '-' + month + '-' + day
      return returnDate
    },

获取指定月份最后一天

//获取指定时间的最后一天
getCurrentMonthLast (date){
     var endDate = new Date(date); //date 是需要传递的时间如:2018-08
     var month=endDate.getMonth();
     var nextMonth=++month;
     var nextMonthFirstDay=new Date(endDate.getFullYear(),nextMonth,1);
     var oneDay=1000*60*60*24;
     var dateString=new Date(nextMonthFirstDay-oneDay);
     console.log(dateString) //Wed Oct 31 2018 00:00:00 GMT+0800 (中国标准时间)
     return dateString.toLocaleDateString(); //toLocaleDateString() 返回 如:2018/8/31
 
    };
   var dateYar=getCurrentMonthLast("2018-08");
   var end=dateYar.replace(new RegExp('/','g'),"-"); //把2018/8/31 替换成2018-8-31

你可能感兴趣的:(js日期操作)