Let say I have a date range that has a specified start and end date. I want to loop through each day, and each loop I will add the date to an empty object(2) and once the length of object(2) has reach a specific length I want to push obj(2) to the main object(1) and continue with the loop.
var startDate = new Date('Tue Oct 18 2022 00:00:00 GMT 0800');
var endDate = new Date('Tue Nov 16 2022 00:00:00 GMT 0800');
var week = [] (object(2))
var weekObj= [] (object(1))
So what I did was this,
for(var d = startDate; d <= endDate; d.setDate(d.getDate() 1)) {
if(week.length === 7) {
weekObj.push(week)
} else {
function removeTime(date) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate()
)
}
let date = removeTime(d)
week.push(date)
}
}
console.log(week)
console.log(week.length)
I was expecting a result like this
[
[
"2022-10-18T16:00:00.000Z",
"2022-10-19T16:00:00.000Z",
"2022-10-20T16:00:00.000Z",
"2022-10-21T16:00:00.000Z",
"2022-10-22T16:00:00.000Z",
"2022-10-23T16:00:00.000Z",
"2022-10-24T16:00:00.000Z"
],
[
"2022-10-25T16:00:00.000Z",
"2022-10-26T16:00:00.000Z",
"2022-10-27T16:00:00.000Z",
"2022-10-28T16:00:00.000Z",
"2022-10-29T16:00:00.000Z",
"2022-10-30T16:00:00.000Z",
"2022-10-31T16:00:00.000Z"
]
.... an so on , until it finishes the loop
But instead it, the loop is already breaking after giving the first seven days.
CodePudding user response:
var startDate = new Date('Tue Oct 18 2022 00:00:00 GMT 0800');
var endDate = new Date('Tue Nov 16 2022 00:00:00 GMT 0800');
var week = [];
var weekObj = [];
for (var d = startDate; d <= endDate; d.setDate(d.getDate() 1)) {
if (week.length === 7) {
weekObj.push(week);
week = [];
} else {
function removeTime(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}
let date = removeTime(d);
week.push(date);
}
}
console.log(week);
console.log(week.length);
console.log(weekObj);
You missed reinitializing the array week
after pushing it to weekObj
.
weekObj.push(week);
week = [];
CodePudding user response:
Thank for the response, it turns out that I can use splice and while loop for this problem.
var weekObj = []
var weeks = []
for(var d = startDate; d <= endDate; d.setDate(d.getDate() 1)) {
function removeTime(date) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate()
)
}
let date = removeTime(d)
weeks.push(date)
}
while(weeks.length !== 0) {
let lastEle = this.state.periodCount
/* lastEle, is the index of how many should I cut and add to the new
object*/
var arrayEle = weeks.splice(0, lastEle)
weekObj.push(arrayEle)
}