Take the 2-minute tour ×

i have been tinkering with the date object.

I want to add a dynamic amount of days to a day and then get the resulting date as a variable and post it to a form.

var startDate = $('#StartDate').datepicker("getDate");
    var change = $('#numnights').val();
    var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + change);

does everything correctly except the last part. it doesnt add the days onto the day

take this scenario:
startdate = 2011-03-01   
change = 1  
alert change = 1
endDate = 2011-03-11 *it should be 2011-03-02*

thank you to all the quick replies.

converting change variable to an integer did the trick. thank you.


just to extend on this: is there a way to assign a variable a type, such as var charge(int)?

share|improve this question
add comment

4 Answers

up vote 2 down vote accepted

You may have fallen victim to string concatenation.

Try changing your last parameter in the Date constructor to: startDate.getDate() + parseInt(change)

See this example for future reference.

share|improve this answer
changing the variable to an integer worked. however, if the day goes into a new month the month stays the same. –  claw Jan 25 '11 at 4:10
It shouldn't. For example, if you called var dt = new Date(2010, 11, 32); your dt object will contain January 1, 2011. The Date constructor handles overflow of months and days. I can set up an example for you to see if you like. –  nybbler Jan 25 '11 at 4:21
please do. id like to know how this works –  claw Jan 25 '11 at 4:26
Hopefully this example helps clear things up for you: webdevout.net/test?01d –  nybbler Jan 25 '11 at 4:41
// NOTE: Months are indexed from 0. So 0 = January and 11 = December this examples a lot! :) –  claw Jan 25 '11 at 5:11
add comment

convert change to a number before adding it. it looks like you're getting a string concatenation operation rather than the addition you're expectingin your code.

share|improve this answer
add comment

I believe you are concatenating instead of using the mathematical operator. Try this instead,

var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + (+change));
share|improve this answer
add comment

It looks like you are not adding the ending day, you are concatinating it so '1' + '1' = '11'

use parseInt() to make sure you are working with integers


var change = parseInt($('selector').val());

Also, with this solution, you could easily end up with a day out of range if you are say on a start date of the 29th of the month and get a change of 5

share|improve this answer
add comment

Your Answer


