需求:
前端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'));