0

I'm trying to generate an array of times by adding 30 min repeatedly. When I do this:

let t = new Date();
    t.setHours(0, 0, 0, 0);
    t.setHours(7);
    t.setMinutes(t.getMinutes() + 30);

I get a time representing 7:30AM. However when I do this:

let t = new Date();
    t.setHours(0, 0, 0, 0);
    t.setHours(7);
    let x = [];
    while (t.getHours() <= 22) {
      t.setMinutes(t.getMinutes() + 30);
      x.push(t);
    }
    return x;

I get 30 or so items that are all 11:00PM. I'm guessing its because they are all referring to the same object instead of copying the object. Using for loop does the same thing.

How would I go about getting my desired result of an array of different times?

3 Answers 3

2

Because you are pushing the same instance of a "Date" object, t onto your array on each iteration of the loop. Each time you modify t, you are effectively modifying all the instances in your array.

You want to push a new instance of Date on each iteration of the loop. The Date class in Javascript appears to happily accept another Date instance as a constructor param, so the fix is quite easy:

Simply change this line:

x.push(t);

To this:

x.push(new Date(t));

Full solution:

let t = new Date();
t.setHours(0, 0, 0, 0);
t.setHours(7);
let x = [];
while (t.getHours() <= 22) {
  t.setMinutes(t.getMinutes() + 30);
  x.push(new Date(t));
}
return x;
Sign up to request clarification or add additional context in comments.

Comments

0
Array.from({length: 500}, (_, i) => new Date(Date.now() + i*1000*60*30))

2 Comments

Please add details to your answer.
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
0

It's beacause you are pushing the same t in your array, each time. Instead of

t.setMinutes(t.getMinutes() + 30);

use

let addedTimeInMilliSeonds = t.setMinutes(t.getMinutes() + 30);

x.push(new Date(addedTimeInMilliSeonds ));`

and you should be fine. (If you do not need t's previous values anymore)

Comments

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.