0

I have a url parameter called commencing date in the format of dd-mm-yyyy. I have input fields in my html field and I need to set dates to those input fields. I need to dates to be set like this. If the commencing date(url parameter string) is 01-01-2014 , the first input field should have the date of 15-02-2015. That means 1 month and 2 weeks later. Then the next input field should have the date 1 month and 2 weeks after the 15-02-2014. This should happen say 10 times. I am doing it using a for loop.I have assigned jquery datepicker for my input fields.

var initialDate = "01-01-2014";
var x;
for(x=1; x<= 10;x++){


   var dateArray = initialDate.split("-");
   var dateObj = new Date(dateArray[2],dateArray[1],dateArray[0]);
   dateObj.setMonth(dateObj.getMonth()+1);
   dateObj.setDate(dateObj.getDate()+14);  

   // Assign the new date value to input field.
   $("#dateOf_installment_"+x).val(dateObj.getDate()+"-"+dateObj.getMonth()+"-"+dateObj.getFullYear());

}

But this does not give me the required values. How to solve this problem, Thanks all!

vigamage
  • 1,975
  • 7
  • 48
  • 74

1 Answers1

1

2 problems with your code -

The Date object uses 0-11 instead of 1-12 for months Jan-Dec. So when you set the month of the date object, you need to subtract 1 to set the correct month. When you convert the month back to Jan-Dec 1-12, you'll need to add back the 1.

Also, I updated your code a little so that the loop will continue working correctly. This loop goes 3 iterations, but should be expandable to 10.

Lastly, if your answers come out different then expected, this thread might be the cause of the issue. How to add number of days to today's date?

JS Fiddle: http://jsfiddle.net/biz79/bteL6138/

var initialDate = "01-01-2014";
var lastDate = initialDate;
var x;

for (x = 1; x <= 3; x++) {
    var dateArray = lastDate.split("-");

    // sub 1 from month
    var dateObj = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);

    dateObj.setMonth(dateObj.getMonth() + 1);
    dateObj.setDate(dateObj.getDate() + 14);

    // add 1 for month
    lastDate = dateObj.getDate() + "-" + (dateObj.getMonth() + 1) + "-" + dateObj.getFullYear();              

    $("#dateOf_installment_" + x).val(lastDate);
}
Community
  • 1
  • 1
Will
  • 1,299
  • 9
  • 9