1

Im making an array that stores a start time and times following that in 40 min intervals.

Basically check, add the start time to the array then increment repeat.

  //Array Of All Available times.
  var timeArray = [];
  //Start time this begins with 9:00
  var startTime = new Date(`date setup here`);
  //End Time this is 17:00
  var endTime = new Date(`date setup here`);
  while (startTime < endTime) {
    //Push Start Time to Array
    timeArray.push(startTime);
    //Add 40 minutes to startTime
    startTime = new Date(startTime.setMinutes(startTime.getMinutes() +40));
  }

Here are screenshots of the logs:

Start and end Times:

img

Log of Array:

img2

In the array I find it strange why the inital start time of 9 is not index 0 and why the last index is the end time which should of failed the while loop condition.

1 Answer 1

6

In your loop:

while (startTime < endTime) {
    //Push Start Time to Array
    timeArray.push(startTime);
    //Add 40 minutes to startTime
    startTime = new Date(startTime.setMinutes(startTime.getMinutes() +40));
}

the last line modifies the startTime Date object before it assigns the new Date to the variable. Thus, when the .push() happens the date is correct, but it changes in that last line of the loop.

Instead, make a new date first and then change it:

while (startTime < endTime) {
    //Push Start Time to Array
    timeArray.push(startTime);
    //Add 40 minutes to startTime
    startTime = new Date(startTime);
    startTime.setMinutes(startTime.getMinutes() +40));
}
Sign up to request clarification or add additional context in comments.

1 Comment

This was it thanks a lot for the suggestion it was such a small fix!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.