最近刚做了一个H5的项目,项目需求是希望预约时间最晚为明天18点前,通过写了个简单的验证方法来执行。
var time = $("#time").val();//选择框内的值
var tomorrowd=new Date();//当前时间
var hourTime = new Date(time.replace(/\-/g, "\/"));//替换"-"为"/"的当前时间
var d1 = new Date(time.replace(/\-/g, "\/"));//替换"-"为"/"的选择时间
//setDate() 方法用于设置一个月的某一天。
//在此设置明天的18:01:00
tomorrowd.setDate(tomorrowd.getDate()+1);
tomorrowd.setHours(18);
tomorrowd.setMinutes(0);
tomorrowd.setSeconds(1);
tomorrowd.setMilliseconds(0);
//将时间转换为时间戳
console.log('选择的时间戳:'+d1.getTime());
console.log('明天18点的时间戳:'+tomorrowd.getTime());
console.log('半小时的时间戳:'+new Date().getTime()+ 1000*60*30);
//验证判断
if (time == null || time === '') {
webToast("请选择预约时间!");
return false;
}
if (hourTime.getHours() < 9 || hourTime.getHours() > 18 ||(hourTime.getHours() === 18 && hourTime.getMinutes() !==0)){
webToast("请选择工作时间9:00-18:00!");
return false;
}
if(d1.getTime() < new Date().getTime()+ 1000*60*30){
webToast("请选择当前时间至少延后30分钟!");
return false;
}
if(d1.getTime() > tomorrowd.getTime()){
webToast("预约时间最晚可选择明天18点前!");
return false;
}