javascriptjquerydatejs

Date js cannot add months


Hi everyone I use Date js library and have a problem with adding additional months.

Here my simple code:

var durationMonth = $('#periodId').find(':selected').data('id'); // value => 3 m
var startDate = $('#comencingDate').val(); // value -> 2015.12.14
$('#expiringDate').val(Date.parse(startDate + ' + ' + durationMonth).toString("yyyy-MM-dd")); 
// This return 2016-03-03, but have to return 2016-03-13

Here little demo http://jsfiddle.net/d9rttxta/1/

The problem is only with months, with days and years work ok. If you have any suggestion I will be very glad to hear. Thanks in advance.

Expected Result: 2016-03-13

Actual Result: 2016-03-03


Solution

  • Adding the month to a date would reset the date-month to the 1st day of the month. So you need to extract the day part out of the value and then append it with the month value.

    $('.change').on('click', function() {
                var durationMonth = $('#periodId').find(':selected').data('id');      
                var startDate = $('#comencingDate').val();
                $('#expiringDate').val(Date.parse(Date.parse(startDate).toString("dd") + ' + ' + durationMonth).toString("yyyy-MM-dd"));
    });
    

    Working example : http://jsfiddle.net/d9rttxta/3/

    UPDATE : In order to add a month to a date which is in future year, here's what you can try :

    $('.change').on('click', function() {
                var durationMonth = $('#periodId').find(':selected').data('id');      
                var startDate = $('#comencingDate').val();
          var monthDiff = Date.parse(startDate).getMonth() - new Date().getMonth()
           + (12 * (Date.parse(startDate).getFullYear() - new Date().getFullYear())); 
    
          var calcDate = Date.parse(Date.parse(startDate).toString("dd") + ' + ' + durationMonth).toString("yyyy-MM-dd");  
    
          if(monthDiff > 0)
          {
             var n_calcDate = new Date(calcDate);
             n_calcDate.setMonth(n_calcDate.getMonth() + monthDiff);
             n_calcDate.setDate(n_calcDate.getDate() + 1);
             calcDate = n_calcDate.toString("yyyy-MM-dd");
          }
    
                $('#expiringDate').val(calcDate);
    });
    

    Working example : http://jsfiddle.net/d9rttxta/5/