0

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();
    alert(change);
    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.

parseInt(change)

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

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

changing the variable to an integer worked. however, if the day goes into a new month the month stays the same.
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.
Hopefully this example helps clear things up for you: webdevout.net/test?01d
// NOTE: Months are indexed from 0. So 0 = January and 11 = December this examples a lot! :)
1

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.

Comments

1

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

Comments

1

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

example

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.