JS 获得两个时间间隔天数


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>

</head>
<body>
<input type=text value="2008-02-04" id="gmtStartDay">
<input type=text value="2008-03-04" id ="gmtEndDay">
<input type=button id=bt value="OK" onclick="javascript:checkDiffDays();"/>
</body>
<script language=javascript>

//计算两个日期的差值,并弹出窗口,提醒错误
function checkDiffDays() {
var gmtStartDay = document.getElementById("gmtStartDay").value;
var gmtEndDay = document.getElementById("gmtEndDay").value;
var diffDays = getDiffDays(gmtStartDay,gmtEndDay);
if (diffDays > 90) {
alert("间隔时间无效,间隔时间不能大于90天!");
return false;
}
alert(diffDays);
return true;
}


//得到两个日期的间隔时间的天数
function getDiffDays(date1,date2) {
var regexp=/^(\d{1,4})[-|\.]{1}(\d{1,2})[-|\.]{1}(\d{1,2})$/;
var monthDays=[0,3,0,1,0,1,0,0,1,0,0,1];
regexp.test(date1);
var date1Year=RegExp.$1;
var date1Month=RegExp.$2;
var date1Day=RegExp.$3;

regexp.test(date2);
var date2Year=RegExp.$1;
var date2Month=RegExp.$2;
var date2Day=RegExp.$3;

if (validatePeriod(date1Year,date1Month, date1Day, date2Year, date2Month, date2Day)) {
var firstDate = new Date(date1Year, date1Month, date1Day);
var secondDate = new Date(date2Year, date2Month, date2Day);

var result = Math.floor((secondDate.getTime() - firstDate.getTime()) / (1000*3600*24));
for(j = date1Year; j < date2Year; j++) {
if (isLeapYear(j)) {
monthDays[1] = 2;
} else {
monthDays[1] = 3;
}
for(i = date1Month -1 ; i < date2Month; i++) {
result = result - monthDays[i]
}
}
return result;
} else {
return ;
}
if(validatePeriod(date1Year,date1Month,date1Day,date2Year,date2Month,date2Day)){
firstDate=new Date(date1Year,date1Month,date1Day);
secondDate=new Date(date2Year,date2Month,date2Day);

result=Math.floor((secondDate.getTime()-firstDate.getTime())/(1000*3600*24));
for(j=date1Year;j<=date2Year;j++){
if(isLeapYear(j)){
monthDays[1]=2;
}else{
monthDays[1]=3;
}
for(i=date1Month-1;i<date2Month;i++){
result=result-monthDays[i];
}
}
return result;
}else{
return 'the first field must before the second date.';
}
}

//判断年份是否是闰年
function isLeapYear(year) {
if (year % 4 == 0 && (year % 100 != 0) || (year % 400 == 0)) {
return true;
}
return false;
}

//判断前后两个日期
function validatePeriod(fyear, fmonth, fday, byear, bmonth, bday) {
if (fyear < byear) {
return true;
} else if (fyear == byear) {
if (fmonth < bmonth) {
return true;
} else if (fmonth == bmonth) {
if (fday <= bday) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
</script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值