0

Hello I have date in this format 03/08/12 where 03 is month, 08 is day and 12 is year. Now I want to add days in it. I have tried following but not getting the exact result

  checkindate = new Date($("#checkindate").val());
  checkindate.setDate(checkindate.getDate()+no_of_nights);
  $("#checkoutdate").val((checkindate.getMonth()+1)+"/"+checkindate.getDate()+"/"+checkindate.getYear());

But is is giving unexpected result and I am unable to understand in which part of date it is adding. Can Any body tell me how can I do this?

Regards

user1272333
  • 33
  • 1
  • 5
  • potential duplicate of http://stackoverflow.com/questions/563406/add-days-to-datetime-using-java-script – jbabey Mar 15 '12 at 18:51

2 Answers2

0

What you have now will not work in all situations because you are adding the no_of_nights to the Day value which means you could have 31 + 5, setDate() will not give you the expected outcome with a value of 36.

You must figure out how many months, days, years, etc. you want to add.

Javascript works off of miliseconds from 1/1/1970 and not normal time.

bdparrish
  • 3,216
  • 3
  • 37
  • 58
  • dude no_of_nights is a variable which means no of days. I didn't understand you answer.Can you please explain? – user1272333 Mar 15 '12 at 18:55
  • @user1272333, I understand what the variable is, but read the documentation on setDate() it accepts values 1-31. So if you get the current date as March 31, and then you add the variable, say 5 days, you end up with 36 days, which javascript will not add correctly to the date object, that is why you are getting an unexpected result. The setDate() method assumes you are just trying to set the day value of the Date object within the current month that it is set to. it doesn't understand 36 as an input parameter. – bdparrish Mar 15 '12 at 20:46
0

Your code works perfectly, but make sure no_of_nights is not a string. That's probably your issue: the addition operation checkindate.getDate()+no_of_nights becomes a concatenation operation if no_of_nights is a string.

8 + 5 = 13
8 + "5" = "85"

Very different!

Solution: use parseInt(no_of_nights).

apsillers
  • 112,806
  • 17
  • 235
  • 239