最近碰到一些企业网站需要定时开启关闭的需求,可能是网站维护或者是网站做整改需要特定的时间网站才开启访问,其余时间都是关闭状态。
JS实现方式,代码如下:
<script language="javascript" type="text/javascript">
// 以下方式定时跳转
var myTime = {
beginDateStr:'2023/06/20',
endDateStr:'2023/07/10',
beginTimeStr:'6:00',
endTimeStr:'22:00'
}
function isDuringDate(beginDateStr, endDateStr){
var curDate = new Date(),
beginDate = new Date(beginDateStr),
endDate = new Date(endDateStr);
if (curDate >= beginDate && curDate <= endDate) {
return true;
}
return false;
}
function checkAuditTime(beginTime, endTime) {
var nowDate = new Date();
var beginDate = new Date(nowDate);
var endDate = new Date(nowDate);
var beginIndex = beginTime.lastIndexOf("\:");
var beginHour = beginTime.substring(0, beginIndex);
var beginMinue = beginTime.substring(beginIndex + 1, beginTime.length);
beginDate.setHours(beginHour, beginMinue, 0, 0);
var endIndex = endTime.lastIndexOf("\:");
var endHour = endTime.substring(0, endIndex);
var endMinue = endTime.substring(endIndex + 1, endTime.length);
endDate.setHours(endHour, endMinue, 0, 0);
if (nowDate.getTime() - beginDate.getTime() >= 0 && nowDate.getTime() <= endDate.getTime()) {
return true;
} else {
return false;
}
}
if(!isDuringDate(myTime.beginDateStr, myTime.endDateStr)){
window.location.href="/404";
}else{
if(!checkAuditTime(myTime.beginTimeStr, myTime.endTimeStr)){
window.location.href="/404";
}
}
</script>
其中开启与关闭日期请在这部分代码设置即可:
beginDateStr:'2023/06/20',
endDateStr:'2023/07/10',
beginTimeStr:'6:00',
endTimeStr:'22:00'