How can we get previous and next months with full days continuously using moment js?

1.9k Views Asked by At

I have two buttons for getting next and previous months with fulldays. I have included moment js. At-present when I click on next button I am getting December and end date is 28th, then I click again getting the same month not January. When I click on previous button October is getting, then I click again getting the same month not September.

$('.datepicker__month-button--next').on('click', function () {
    console.log('next');
    console.log(moment().add(1, 'months'));
});

 $('.datepicker__month-button--prev').on('click', function () {
     console.log('prev');
     console.log(moment().subtract(1, 'months'));
 }); 
1

There are 1 best solutions below

3
On BEST ANSWER

You can do it like below:

var seletedDate = moment(new Date());

$(document).ready(function() {
    alert(seletedDate);
});

$('#next').click(function() {
     var lastDayOfNextMonth = moment(seletedDate.add(1,"M")).endOf('month');
     // Update selected date
     seletedDate = lastDayOfNextMonth;
    alert(seletedDate);
});

$('#pre').click(function() {
    var lastDayOfPreviousMonth = moment(seletedDate.add(-1,"M")).endOf('month');
    // Update selected date
    seletedDate = lastDayOfPreviousMonth;
    alert(seletedDate);
});

Online demo (fiddle)