Periodical events with Moment.js and Angular.js

1

Greetings

I am making an application in which I have to manage a calendar with events that repeat themselves, but I am having problems when generating the events that repeat on the 31st of each month, since there are months that do not have 31 days, the ideal would be that in those months the day will be set to the last day of the month.

EJ:

var interval = moment("2016-12-31T08:00:00");
console.log(interval.format())
console.log(interval.add(1, 'month').date(31).format())
console.log(interval.add(1, 'month').date(31).format())
console.log(interval.add(1, 'month').date(31).format())
console.log(interval.add(1, 'month').date(31).format())
console.log(interval.add(1, 'month').date(31).format())
console.log(interval.add(1, 'month').date(31).format())
console.log(interval.add(1, 'month').date(31).format())

I get

2016-12-31T08:00:00-05:00
2017-01-31T08:00:00-05:00
2017-03-03T08:00:00-05:00 //MAl
2017-05-01T08:00:00-05:00 //MAl
2017-07-01T08:00:00-05:00 //MAl
2017-08-31T08:00:00-05:00
2017-10-01T08:00:00-05:00 //MAl
2017-12-01T08:00:00-05:00 //MAl

There are months that do not come out, but note that if I do this:

var interval = moment("2016-12-31T08:00:00");
console.log(interval.format())
console.log(interval.add(1, 'month').date(31).format());
console.log(interval.date(31).add(1, 'months').format());
console.log(interval.add(1, 'month').date(31).format());
console.log(interval.date(31).add(1, 'months').format());
console.log(interval.add(1, 'month').date(31).format());
console.log(interval.date(31).add(1, 'months').format());
console.log(interval.add(1, 'month').date(31).format());
console.log(interval.date(31).add(1, 'months').format());
console.log(interval.add(1, 'month').date(31).format());

That is, alternating between first setting the day and then adding the month, I get the desired operation until the month of August

2016-12-31T08:00:00-05:00
2017-01-31T08:00:00-05:00
2017-02-28T08:00:00-05:00
2017-03-31T08:00:00-05:00
2017-04-30T08:00:00-05:00
2017-05-31T08:00:00-05:00
2017-06-30T08:00:00-05:00
2017-07-31T08:00:00-05:00
2017-08-31T08:00:00-05:00
2017-10-01T08:00:00-05:00 //MAl

Some idea of how to get the desired performance, thank you in advance.

    
asked by Cristian C 29.11.2016 в 10:33
source

1 answer

1

If you want to get the last day of the month you can use better endOf('month') :

var interval = moment("2016-12-31T08:00:00");
console.log(interval.format())
console.log(interval.add(1, 'month').endOf('month').format());
console.log(interval.add(1, 'month').endOf('month').format());
console.log(interval.add(1, 'month').endOf('month').format());
console.log(interval.add(1, 'month').endOf('month').format());
console.log(interval.add(1, 'month').endOf('month').format());
console.log(interval.add(1, 'month').endOf('month').format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>
    
answered by 29.11.2016 / 11:42
source