简体   繁体   中英

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

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'));
 }); 

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM