用来计算时间差的js代码片段

代码片段(1)[全屏查看所有代码]

1. [代码]本代码初步测试可用，欢迎大神检验修改，谢谢     跳至 [1] [全屏预览]

```function dealDate(date1,date2){
date1 = new Date(date1);//如果传进来的是"yyyy-MM-dd"形式的字符串
date2 = new Date(date2);
var year1 = date1.getFullYear();
var month1 = date1.getMonth()+1;
var day1 = date1.getDate();
var dateMax1 = new Date(year1,month1,0);
var dayMax1 = dateMax1.getDate();
var year2 = date2.getFullYear();
var month2 = date2.getMonth()+1;
var day2 = date2.getDate();
var dateMax2 = new Date(year2,month2,0);
var dayMax2 = dateMax2.getDate();
if(day1==dayMax1&&day2==dayMax2){
//开始日期和结束日期都是月底
//直接计算月份差，推算几年几个月
var res = (year2-year1)*12+(month2-month1);//月份差
var difYear = Math.floor(res/12);
var difMonth = res%12;
return ((difYear!=0)?(difYear+"年"):"")+difMonth+"个月";
}else if(day1==dayMax1&&day2<dayMax2){
//开始日期是月底，结束日期不是
//计算开始日期到结束日期上一个月的月底,再加上结束日期的天数
var month3 = month2-1;
var res = (year2-year1)*12+(month3-month1);//月份差
var difYear = Math.floor(res/12);
var difMonth = res%12;
var difDay = day2;
return ((difYear!=0)?(difYear+"年"):"")+((difMonth!=0)?(difMonth+"个月"):"")+difDay+"天";
}else if(day1<dayMax1&&day2<dayMax2){
//开始日期和结束日期都不是月底
//情况1,day1<day2
if(day1<=day2){
var res = (year2-year1)*12+(month2-month1);//月份差
var difYear = Math.floor(res/12);
var difMonth = res%12;
var difDay = day2-day1;
return ((difYear!=0)?(difYear+"年"):"")+((difMonth!=0)?(difMonth+"个月"):"")+difDay+"天";
}else{
var month3 = month2-1;
var res = (year2-year1)*12+(month3-month1);//月份差
var difYear = Math.floor(res/12);
var difMonth = res%12;
var difDayTemp = day1-day2;
var dateMax3 = new Date(year2,month3,0);
var dayMax3 = dateMax3.getDate();
var difDay = dayMax3-difDayTemp;
return ((difYear!=0)?(difYear+"年"):"")+((difMonth!=0)?(difMonth+"个月"):"")+difDay+"天";
}
}
}```