Javascript: Adding days to any date

Go To StackoverFlow.com

2

I've read through a number of topics now and have not found one quite on point.

Here's what I'm trying to do:
1) Parse a bill date that is provided in the format mm/dd/yy and is frequently not today
2) Add a variable number of days to the date. The terms are saved in the dueTime array below. I limited it to 30 days here.
3) Based on the bill date + the payment terms, calculate the date that the bill is due and return that in the mm/dd/yy format.

Here's what I've tried. The information I pass into new Date is what I expect, but the output from new date is never what I expect.

Thanks for your help.

<html>
<head>
<script>
function calculateDueTime(){
    var billDate = document.getElementById('billDateId').value;
    var key = document.getElementById('termsId').value;
    var dueTime = new Array();
    dueTime[1] = 30;
    var billDate = billDate.split('/');
    var newDate = new Date( parseInt( billDate[2] ) + '/' + parseInt( billDate[0] ) + '/' + ( parseInt( billDate[1] ) + parseInt( dueTime[key] ) ) ); 
    document.getElementById('dueDateId').value = newDate.toString();
}
</script>
</head>
<body>

<input name="billDate" id="billDateId" value="5/1/11" /> 
Or any value in mm/dd/yy or m/d/yy format
<select name="terms" id="termsId" onchange="calculateDueTime()">
   <option value="1">Net 30</option>
</select>
<input name="dueDate" id="dueDateId" />

</body>
</html>
2012-04-04 19:53
by phpmeh


1

I would suggest taking a look at Datejs (http://www.datejs.com/). I use this library quite a bit to deal with dates, which I find to be a real pain in JS.

2012-04-04 19:56
by BradBrening
That is a fantastic library! Thank - phpmeh 2012-04-04 20:24


5

Just add the number of days to the date:

var dt= new Date();

dt.setDate(dt.getDate() + 31);

console.log(dt);
2012-04-04 19:58
by Tuan
d = new Date() Fri Feb 13 2015 12:26:54 GMT+0200 d.setDate(13-20) Sat Jan 24 2015 12:26:54 GMT+0200

doesn't seem as a good wa - Gena Moroz 2015-02-13 10:27

Ads