phpmeh
phpmeh

Reputation: 1792

Javascript: Adding days to any date

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>

Upvotes: 2

Views: 2758

Answers (2)

Tuan
Tuan

Reputation: 5412

Just add the number of days to the date:

var dt= new Date();

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

console.log(dt);

Upvotes: 5

BradBrening
BradBrening

Reputation: 5518

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.

Upvotes: 1

Related Questions