废话不多说,直接上菜!
//PS :这里需要注意的是 周日 是 0 !!!!!
console.log(getBeforeDate(-10000)) //一万天之后的日期
console.log(getWeek('2019-07-03',[2,3],20))//从'2019-07-03' 开始获取之后 20 个 周二、周三的日期
/**
* 获取某个时间开始 之后的 N次[周几,周几]
* @param {Object} begin 开始时间
* @param {Object} week_arr 需要获取的周几数组
* @param {Object} Max 需要获取数组最大长度
*/
function getWeek (begin, week_arr,Max){
var dateArr = new Array();
var stimeArr = begin.split("-");//=>["2018", "01", "01"]
var etimeArr = getBeforeDate(-10000).split("-");//=>["2018", "01", "30"] 这里我给了一个10000天后的一起可更具需求更改
var stoday = new Date();
stoday.setUTCFullYear(stimeArr[0], stimeArr[1]-1, stimeArr[2]);
var etoday = new Date();
etoday.setUTCFullYear(etimeArr[0], etimeArr[1]-1, etimeArr[2]);
var unixDb = stoday.getTime();//开始时间的毫秒数
var unixDe = etoday.getTime();//结束时间的毫秒数
for (var k = unixDb; k <= unixDe;) {
//达到最大次数时,结束循环
if(dateArr.length==Max){
break;
}else{
let needJudgeDate = msToDate(parseInt(k)).withoutTime;
//不加这个if判断直接push的话就是已知时间段内的所有日期
$.each(week_arr, function(i,o) {
if (new Date(needJudgeDate).getDay() === o) {
dateArr.push(needJudgeDate);
}
})
k = k + 24*60*60*1000;
}
}
return dateArr;
}
//根据毫秒数获取日期
function msToDate (msec) {
let datetime = new Date(msec);
let year = datetime.getFullYear();
let month = datetime.getMonth();
let date = datetime.getDate();
let hour = datetime.getHours();
let minute = datetime.getMinutes();
let second = datetime.getSeconds();
let result1 = year +
'-' +
((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
'-' +
((date + 1) < 10 ? '0' + date : date) +
' ' +
((hour + 1) < 10 ? '0' + hour : hour) +
':' +
((minute + 1) < 10 ? '0' + minute : minute) +
':' +
((second + 1) < 10 ? '0' + second : second);
let result2 = year +
'-' +
((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
'-' +
((date + 1) < 11 ? '0' + date : date);
let result = {
hasTime: result1,
withoutTime: result2
};
return result;
}
//-----[获取前n天的日期]
function getBeforeDate(n) {
var n = n;
var d = new Date();
var year = d.getFullYear();
var mon = d.getMonth() + 1;
var day = d.getDate();
if(day <= n) {
if(mon > 1) {
mon = mon - 1;
} else {
year = year - 1;
mon = 12;
}
}
d.setDate(d.getDate() - n);
year = d.getFullYear();
mon = d.getMonth() + 1;
day = d.getDate();
s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
return s;
}
//-----[获取前n天的日期END]