最近在写一个自动排班功能,要求超过某设定的时间点后,自动计入下一个周期。以下为核心JS代码:
说明:
- 本例中设置的超时时间点为每周五17:20;
- 本例中设置的间隔周期为7天
- 本例返回的格式为JS中的date类型(非格式化String)
//Get next date(liangxin 2020-09-11)
//Out JS date format
function getNextDate(){
var now = new Date();
var year = now.getFullYear();
var date= now.getDate();
var month = now.getMonth();
var day = now.getDay();
var hour = now.getHours();
var minute = now.getMinutes();
if(day == 5 && hour == 15 && minute >20 ){
var nextDate = AddDays(getDate(year+"-"+month+"-"+date+" 00:00:00"),7)+" 17:00:00" ;
return getDate(nextDate);
}else{
return getDate(year+"-"+month+"-"+date+" 17:00:00");
}
}
//Date add days
function AddDays(date,days){
var nd = new Date(date);
nd = nd.valueOf();
nd = nd + days * 24 * 60 * 60 * 1000;
nd = new Date(nd);
var y = nd.getFullYear();
var m = nd.getMonth();
var d = nd.getDate();
if(m <= 9) m = "0"+m;
if(d <= 9) d = "0"+d;
var cdate = y+"-"+m+"-"+d;
return cdate;
}
//String to date foramt
function getDate(strDate) {
var st = strDate;
var a = st.split(" ");
var b = a[0].split("-");
var c = a[1].split(":");
var date = new Date(b[0], b[1], b[2], c[0], c[1], c[2]);
return date;
}
//格式化输出 JSON
console.log(getNextDate());