JS1986
JS1986

Reputation: 1950

manipulating date object with javascript

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

Upvotes: 0

Views: 250

Answers (4)

jondavidjohn
jondavidjohn

Reputation: 62392

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

Upvotes: 1

Lance
Lance

Reputation: 1897

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

Upvotes: 1

Metal
Metal

Reputation: 903

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.

Upvotes: 1

nybbler
nybbler

Reputation: 4841

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.

Upvotes: 2

Related Questions