js获取一段时间内的间隔日期
需求:
前端js,已知开始时间a、结束时间b和间隔天数c,要求取在a-b这两个时间范围内、间隔c天的所有日期。
代码:
// startDate: 计划开始时间; endDate:计划结束时间;dayLength:每隔几天,0-代表每天,1-代表日期间隔一天
function getDateStr(startDate, endDate, dayLength) {
var str = startDate;
for (var i = 0 ;; i++) {
var getDate = getTargetDate(startDate, dayLength);
startDate = getDate;
if (getDate <= endDate) {
str += ','+getDate;
} else {
break;
}
}
console.log(str);
}
// startDate: 开始时间;dayLength:每隔几天,0-代表获取每天,1-代表日期间隔一天
function getTargetDate(date,dayLength) {
dayLength = dayLength + 1;
var tempDate = new Date(date);
tempDate.setDate(tempDate.getDate() + dayLength);
var year = tempDate.getFullYear();
var month = tempDate.getMonth() + 1 < 10 ? "0" + (tempDate.getMonth() + 1) : tempDate.getMonth() + 1;
var day = tempDate.getDate() < 10 ? "0" + tempDate.getDate() : tempDate.getDate();
return year + "-" + month + "-" + day;
}
方法调用
getDateStr('2019-07-01', '2019-07-10', 0);
广州品牌设计公司https://www.houdianzi.com PPT模板下载大全https://redbox.wode007.com
其它方式
function getDuration(type,start,stop){
var $array = new Array();
var current = new Date(start);
stop = new Date(stop);
while (current <= stop) {
$array.push( new Date (current) );
if(type == 'hour'){//小时
current.setHours(current.getHours() + 1);
}else if(type == 'day'){//天
current.setDate(current.getDate() + 1);
}else if(type == 'week'){//周
current.setDate(current.getDate() + 7);
}else if(type == 'month'){//月
current.setMonth(current.getMonth() + 1);
}else{//默认天
current.setDate(current.getDate() + 1);
}
}
return $array;
}
console.log(getDuration('day','2019-10-05 10:23:16','2019-11-05 18:23:16'));