js计算两个日期之间的天数

//得到两个日期之间的天数 YYYY-MM-DD - YYYY-MM-DD
function getDateRegion =  function(beginDate,endDate){
   if(beginDate != '' && endDate != ''){
      var aDate, oDate1, oDate2, iDays;
      if(beginDate.length==8){
         beginDate = beginDate.substr(0,4)+'-'+beginDate.substr(4,2)+'-'+beginDate.substr(6,2);
      }
      if(endDate.length==8){
         endDate = endDate.substr(0,4)+'-'+endDate.substr(4,2)+'-'+endDate.substr(6,2);
      }
      aDate = beginDate.split("-");
      oDate1 = new Date(aDate[1] + '/' + aDate[2] + '/' + aDate[0]);   //转换为12/13/2008格式
      aDate = endDate.split("-");
      oDate2 = new Date(aDate[1] + '/' + aDate[2] + '/' + aDate[0]);
      var i=(oDate1 - oDate2) / 1000 / 60 / 60 /24;
      /*if(i<0){
         i-=1;
      }else{
         i+=1;
      }*/
      iDays = i;   //把相差的毫秒数转换为天数
      return iDays; 
   }else{
      return 0;
   }
};
//得到两个日期之间的天数 YYYY-MM-DD - YYYY-MM-DD
Tools.getDateMonthBetween =  function(date1,date2){ 
	if(date1 != '' && date2 != ''){
		var year1 =  date1.substr(0,4);
	  	var year2 =  date2.substr(0,4); 
	  	var month1 = date1.substr(4,2);
	  	var month2 = date2.substr(4,2);
	  	var day1 = date1.substr(6,2);
	  	var day2 = date2.substr(6,2);
	  	var len=(year2-year1)*12+(month2-month1);
	  	if(len>0){
			if(day2 - day1 <= 0){
				len = len - 1;
			}
		}else{
			if(day1 - day2 <= 0){
				len = len + 1;
			}
		}
		return Math.abs(len);
	}else{
		return 0;
	}
};

 

    原文作者:可以简单点
    原文地址: https://blog.csdn.net/weixin_38860401/article/details/106274562
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞