Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Moment.js to make an array of this week's dates doesn't add to array

I'm using Moment.js to make a Resource Calendar and I need an array of dates for this week. The console log of my current function prints out appropriately but the array that gets pushed in for each date is wrong.

    var startOfWeek = moment().startOf('week');
    var endOfWeek = moment().endOf('week');

    var days = [];
    var day = startOfWeek;

    do {
        console.log(day._d);
        days.push(day._d);
        day = day.add(1, 'd');
    }
    while (day <= endOfWeek);

    console.log(days);

Returns:

Sun Jan 18 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Mon Jan 19 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Tue Jan 20 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Wed Jan 21 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Thu Jan 22 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Fri Jan 23 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Sat Jan 24 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
[Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST)]

Notice how the array at the bottom is the next date in the array repeated 7 times.

like image 732
Chris Avatar asked Jan 18 '15 14:01

Chris


1 Answers

As danludwig mentioned in his comment on the question, you are adding a reference for the same date to the array multiple times.

From the Moment.js documentation:

It should be noted that moments are mutable. Calling any of the manipulation methods will change the original moment.

If you want to create a copy and manipulate it, you should use moment#clone before manipulating the moment.

You should be calling the clone function on the Moment date object as shown here.

var startOfWeek = moment().startOf('week');
var endOfWeek = moment().endOf('week');

var days = [];
var day = startOfWeek;

while (day <= endOfWeek) {
    days.push(day.toDate());
    day = day.clone().add(1, 'd');
}

console.log(days);

As an aside:

You should not reference internal fields/functions of a 3rd party library. The name of these references are more likely to change than the public API described in the documentation. _d can be referenced by calling the public function toDate.

like image 53
Taylor Buchanan Avatar answered Oct 26 '22 22:10

Taylor Buchanan