CUH
CUH

Reputation: 147

Moment.js not displaying all dates correctly

I'm trying to display the next upcoming Thursdays using Moment.js and not sure why the middle dates are skipping. For example: instead of display: Sep 3, 10, 17, 24, Oct 1

it instead displays Sep 3, 10, 24, Oct 15, Nov 12, Dec 17, etc...

Here's what I have so far:

var date = moment();
var y = 3;
while (y<56) {
   var nextThursday = date.weekday(y).add(1,"days").format("dddd, MMM Do");
   var addValueThursday = nextThursday;
   var thurs = {"text": addValueThursday};
   console.log(addValueThursday);
   y+=7;
}

Upvotes: 2

Views: 108

Answers (2)

osxi
osxi

Reputation: 278

Here's how I would find the next 10 occurrences of Thursday, starting this week:

   var thursday = moment().startOf('week').add(4, 'days');

   for (var i=0; i<10; i++) {
     console.log(thursday.format("dddd, MMM Do"));
     thursday = thursday.add(1, 'week');
   }

This would console.log something like:

Thursday, Sep 3rd
Thursday, Sep 10th
Thursday, Sep 17th
Thursday, Sep 24th
Thursday, Oct 1st
Thursday, Oct 8th
Thursday, Oct 15th
Thursday, Oct 22nd
Thursday, Oct 29th
Thursday, Nov 5th

jsbin: https://jsbin.com/gojetisawu/1/edit?html,output

Upvotes: 1

jpw
jpw

Reputation: 44911

I believe the answer can be found in what the add function does: Mutates the original moment by adding time

So you keep on incrementing an already incremented (through mutation) date.

One solution would be to reset the date inside the loop:

var y = 3;
while (y<56) {
    var date = moment();
    var nextThursday = date.weekday(y).add(1,"days").format("dddd, MMM Do");
    var addValueThursday = nextThursday;
    var thurs = {"text": addValueThursday};
    console.log(addValueThursday);
    y+=7;
}

This gives an output of:

Thursday, Sep 3rd
Thursday, Sep 10th
Thursday, Sep 17th
Thursday, Sep 24th
Thursday, Oct 1st
Thursday, Oct 8th
Thursday, Oct 15th
Thursday, Oct 22nd

There might be smarter ways to do this, but I'm not that familiar with the moment library.

Upvotes: 2

Related Questions