0

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'));
 }); 
Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
Sarath TS
  • 2,432
  • 6
  • 32
  • 79
  • I created [this](http://jsfiddle.net/ali_soltani/Lzohjdkh/2) for solving your issue but I didn't understand your problem clearly. Is this your problem? – Ali Soltani Nov 28 '17 at 07:39
  • @AliSoltani, Thank you. This is the same result I am getting. My problem is , First time I click on next button then I am getting December and day is 28th. I need result like December 31st. If I click next button again I need January 31st and so on. Hope you get my problem. – Sarath TS Nov 28 '17 at 08:05
  • I edited my answer and I used better way for handling 31 days and 30 days. Please see it again. – Ali Soltani Nov 28 '17 at 09:04

1 Answers1

1

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)

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
  • Thank you. But in you fiddle month is not continuously changing. I have updated your fiddle http://jsfiddle.net/jajro968/7/. Now you can see when we click next and previous button, the date will increment and decrements. But I have a problem in previous button click. Eg If I click next button 4 or 5 times, imagine the month is `may` then I click on previous button I am getting alert of older month. Actually I need `April`. – Sarath TS Nov 30 '17 at 14:19
  • @samsam I edited my answer and fiddle. Please see it again. – Ali Soltani Dec 01 '17 at 05:19
  • @ Ali Soltani, Thank you so much. It is working perfectly. – Sarath TS Dec 01 '17 at 06:17