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

PHP高级技术

 
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<>