2

So I'm trying to add a certain number of days to a date, and I'm getting a strange issue:

var date = new Date();

var newdate = date.getDate() + $('#ddlDays option:selected').val();

date.setDate(newdate);

So if today is 09/29/2010, the Date is 29. But if a user selects "5" from ddlDays, it will assume I am adding strings together, adding 295 days to my date.

I was under the impression that javascript would assume they were integers? Does getDate() return a string instead of an integer?

How can I fix this?

Steven
  • 18,761
  • 70
  • 194
  • 296
  • debugging 101: var newdate = date.getDate() + $('#ddlDays option:selected').val(); alert(newdate);alert(typeof date.getDate());alert(typeof $('#ddlDays option:selected').val()); – epascarello Sep 30 '10 at 01:21

5 Answers5

4

If you just want to add the selected value to the day of the month (i.e. 29 + 5), then you need to parse the string value into an int:

var newdate = date.getDate() + parseInt( $('#ddlDays option:selected').val(), 10);

But if you actually want a new date, rather than an int, as your result, you can do something like this:

date.setDate( date.getDate() + parseInt( $('#ddlDays option:selected').val(), 10);
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • Thanks. I always thought that when adding a number (getDate) and a string (val), JS would convert the string to a number and then add them, but I guess it's the other way around? – Steven Sep 29 '10 at 21:19
2

It is .val() that is returning a String. You can use .parseInt() to convert to a Number.

var newdate = date.getDate() + 
                      (parseInt($('#ddlDays option:selected').val(), 10) || 0);

or

var newdate = date.getDate() + ~~$('#ddlDays option:selected').val();
user113716
  • 318,772
  • 63
  • 451
  • 440
1

No, the getDate() call doesn't return a string, but the val() call does.

You'll need to parse the string to an integer instead:

var newdate = date.getDate() + parseInt($('#ddlDays option:selected').val(), 10);
LukeH
  • 263,068
  • 57
  • 365
  • 409
1

Surround your string value with parseInt. JavaScript will concatenate strings to numbers (see http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference for a thorough run through.)

This should do the trick:

var newdate = date.getDate() + parseInt($('#ddlDays option:selected').val());

or

var newdate = date.getDate() + parseInt($('#ddlDays option:selected').val(), 10);
MikeTheReader
  • 4,200
  • 3
  • 24
  • 38
0

adding days and converting it to a specific format are talked about in this question

Community
  • 1
  • 1
Krishna Chytanya
  • 1,398
  • 1
  • 8
  • 12