js 计算两个时间差

    /*

* 计算两个日期的间隔天数
* BeginDate:起始日期的文本框,格式為:2012-01-01
* EndDate:結束日期的文本框,格式為:2012-01-02
* 返回兩個日期所差的天數
* 調用方法:
* alert("相差"+DateDiff("date1","date2")+"天");
*/    

function DateDiff(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式
            var aDate, oDate1, oDate2, iDays
            aDate = sDate1.split("-")
            oDate1 = new Date(aDate[1] + '/' + aDate[2] + '/' + aDate[0]) //转换为12-18-2006格式
            aDate = sDate2.split("-")
            oDate2 = new Date(aDate[1] + '/' + aDate[2] + '/' + aDate[0])
            //iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数 (firefox不支持。返回NaN)
            var i = (oDate1 - oDate2) / 1000 / 60 / 60 / 24;
            if (i < 0) {
                i -= 1;
            }
            else {
                i += 1;
            }
            iDays = i;   //把相差的毫秒数转换为天数
            //alert(iDays);
            return iDays
        }

 

//获取日期:前天GetDateStr(-2)、昨天GetDateStr(-1)、今天GetDateStr(0)、明天GetDateStr(1)、后天GetDateStr(2)
        function GetDateStr(AddDayCount) {
            var dd = new Date();
            dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
            var y = dd.getFullYear();
            var m = dd.getMonth() + 1; //获取当前月份的日期
            var d = dd.getDate();
            return y + "-" + m + "-" + d;
        }

 

//调用

 var EXECDATE = $('#EXECDATE').datebox('getValue');
            var EXECDATEEND = $('#EXECDATEEND').datebox('getValue');
            var s1 = EXECDATE.substring(0, 4) + "-" + EXECDATE.substring(4, 6) + "-" + EXECDATE.substring(6, 8);
            var s2 = EXECDATEEND.substring(0, 4) + "-" + EXECDATEEND.substring(4, 6) + "-" + EXECDATEEND.substring(6, 8);
            if ((DateDiff(s2, GetDateStr(1))) > 1) {
                alert("结束日期不能晚于【" + GetDateStr(1) + "】");
                return false;
            }

            if (EXECDATE != EXECDATEEND) {
                if ((DateDiff(s2, s1)) > 31) {
                    alert("日期范围超过最大查询天数,最大查询天数为30天!");
                    return false;
                }
            }

posted on 2016-05-04 14:22  张晓虹  阅读(445)  评论(1编辑  收藏  举报

导航