很多时候要动态校验开始结束时间,每次都要写一次,太麻烦,以备后面拷贝使用,
代码作用简介:
开始结束时间,联动,开始时间前后移动,对应结束时间相应变化,时间差30天
html:
<input type="date" placeholder="请输入(From)..." id="txtStartDate" value="${startDate }" onblur="onblurStartDate();" />
<input type="date" placeholder="请输入(To)..." id="txtEndDate" value="${endDate }" onblur="onblurEndDate();" />
js:
<script type="text/javascript">
function onblurStartDate() {
var startDateStr = $("#txtStartDate").val();
var nowDate = new Date().toISOString().substring(0, 10); //当前时间截取操作
var endDateStr = addDate(startDateStr, 29);
if(startDateStr >= nowDate) {
alert("开始时间不能大于等于今天!");
var endDate = addDate(nowDate, -29);
$("#txtStartDate").val(endDate);
return;
}
if(endDateStr >= nowDate) {
$("#txtEndDate").val(nowDate);
return false;
}
$("#txtEndDate").val(endDateStr);
}
function onblurEndDate() {
var endDateStr = $("#txtEndDate").val();
var nowDate = new Date().toISOString().substring(0, 10); //当前时间截取操作
if(endDateStr > nowDate) {
alert("结束时间不能大于今天!");
$("#txtEndDate").val(nowDate);
var startDate = addDate(nowDate, -29);
$("#txtStartDate").val(startDate);
return false;
}
var startDateStr = addDate(endDateStr, -29);
$("#txtStartDate").val(startDateStr);
}
function addDate(date, days) {
var d = new Date(date);
d.setDate(d.getDate() + parseInt(days));
var m = d.getMonth() + 1;
m = parseInt(m) < 10 ? ('0' + m) : m;
var day = parseInt(d.getDate()) < 10 ? ('0' + d.getDate()) : d.getDate();
return d.getFullYear() + '-' + m + '-' + day;
}
</script>
java后台:
@RequestMapping(value = { "/pageInit.do" })
protected String pageInit(final HttpServletRequest request, final HttpServletResponse response) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
request.setAttribute("startDate", sdf.format(TimeUtils.addDate(new Date(), -29)));
request.setAttribute("endDate", sdf.format(new Date()));
return "taskManage/taskindex";
}