<head>
<script>
function OnClick(){
//获取开始日期
var startdate =document.getElementById("startdate").value;
//获取当前日期
var d = new Date();
//获取当前年
var year = d.getFullYear();
//获取当前月,需要+1
var month = d.getMonth() + 1;
var months = month < 10 ? ("0" + month) : month;
var dt = d.getDate();
dt = dt < 10 ? ("0" + dt) : dt;
var today = year + "-" + months + "-" + dt;
document.getElementById("a").value = today;
//获取起始日期的月份
var sMonth = startdate.split("-")[1];
if(sMonth < 10){
sMonth = sMonth.substr(1,2); //去除月份前的0操作 例: 2013-01-01
}
//获取起始日期的年份
var sYear = startdate.split("-")[0];
//月份比较
if(this.getMonths(sYear,sMonth,year,month)>4){
alert("不能查询4个月之前!");
}
document.getElementById("b").value = this.getDays(startdate,today);
}
//计算日期之差
function getDays(strDateStart,strDateEnd){
var strSeparator = "-"; //日期分隔符
var oDate1;
var oDate2;
var iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
var strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
var strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateE - strDateS ) / 1000 / 60 / 60 /24)//把相差的毫秒数转换为天数
return iDays ;
}
//计算月份之差
function getMonths(startYear,startMonth,nowYear,nowMonth){
//规则:(当前年份-起始年份)*12+当前月份-起始月份
var count = (nowYear - startYear)*12 + nowMonth - startMonth;
return count;
}
</script>
</head>
<body>
<table>
<tr>
<td class="formLabel">时间:</td>
<td class="formField">
<input type="text" maxlength="16" class="dateField" name="startdate" id="startdate" value="2013-12-31" />
</td>
<td>
<button class="formButton" id="riskSearch" name="riskSearch" οnclick="OnClick()">查询</button>
</td>
</tr>
<tr>
<td class="formLabel">输出:</td>
<td>
<input type="text" maxlength="16" class="dateField" name="a" id="a" value="" />
</td>
</tr>
<tr>
<td class="formLabel">输出:</td>
<td>
<input type="text" maxlength="16" class="dateField" name="b" id="b" value="" />
</td>
</tr>
</table>
</body>
JS计算时间差,计算月份差的简单案例
最新推荐文章于 2024-08-03 11:36:34 发布