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);

方法參考:JS獲取指定日期前後相隔幾天的日期https://blog.csdn.net/qq_42755868/article/details/91888695

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章