user3214546
user3214546

Reputation: 6831

Days are not added properly with momentJS in JavaScript

I have this code where I want to get next 15 days from the start date

    var fortnightStart = moment("15 04 2015", "DD MM YYYY");

    for (var i = 1; i <= 15; i++) {

        dates.push(fortnightStart.add(i, "days").format("D MMM"));

    }

    console.log(dates);

This is the output

["16 Apr", "18 Apr", "21 Apr", "25 Apr", "30 Apr", "6 May", "13 May", "21 May", "30 May", "9 Jun", "20 Jun", "2 Jul", "15 Jul", "29 Jul", "13 Aug"]

I don't know why its missing a few days.

Upvotes: 1

Views: 1267

Answers (3)

codester
codester

Reputation: 41

The reason you're missing dates is because 'date.add' changes the current variable. E.g.

date = moment("15 04 2015", "DD MM YYYY");
date.add(1, "days");
console.log(date); // This will give you "16 04 2015"

For your code to work correctly, you need to make sure that either:

1) The 'add' method doesn't change your original value by adding to a clone. e.g.

dates.push(fortnightStart.clone().add(i, "days").format("D MMM"));

OR

2) You only add 1 day every loop instead if 'i' days. e.g.

dates.push(fortnightStart.clone().add(1, "days").format("D MMM"));

Upvotes: 2

Benjamin Atkin
Benjamin Atkin

Reputation: 14715

The problem is that .add modifies the object passed in instead of creating a new date. To keep your code in its original style, you need to clone the date before adding to it.

dates.push(fortnightStart.clone().add(i, "days").format("D MMM"));

Or:

dates.push(moment(fortnightStart).add(i, "days").format("D MMM"));

Upvotes: 3

Yauheni Leichanok
Yauheni Leichanok

Reputation: 1769

On every iteration you add i days to your initial date - so it keeps accumulating (+1, +2, +3 etc). You need to add not i but simply 1 to fortnightStart.

var fortnightStart = moment("15 04 2015", "DD MM YYYY");
for (var i = 1; i <= 15; i++) {
    // 1, not i
    dates.push(fortnightStart.add(1, "days").format("D MMM"));
}
console.log(dates);

Upvotes: 6

Related Questions