Javascript add variable date
This should be easy, but I'm looking to add an integer variable called "rental_period" to the current date and then displa开发者_运维技巧y it in DD/MM/YYYY form. This is my code:
duedate.setDate(duedate.getDate()+rental_period);
$("#pricing_due").html("DUE DATE: <strong>" + duedate.getDay() + "/" + duedate.getMonth() + "/" + duedate.getFullYear() + "</strong>");
Javascript datetimes are stored in milliseconds.
Therefore, assuming that rental_period
in a number of days, you need to write
duedate.setTime(duedate.getTime() + rental_period * 24 * 60 * 60 * 1000);
(24 hours × 60 minutes × 60 seconds × 1000 milliseconds)
EDIT: Your code should work as is.
setDate
will only modify the day of the date object. Use something like this instead:
var rentalPeriod, rentedDay, dueDate;
rentalPeriod = 14 * 24 * 3600 * 1000; // in milliseconds, here: 14 days
rentedDay = new Date(); // Date object of when the thing was rented
dueDate = new Date( ( +rentedDay ) + rentalPeriod );
Use this:
duedate.setTime(duedate.getTime() + rental_period);
Make sure rental_period be a value in msecs (can be easily converted from whatever you have, for instance if it's in days, just multiply it by 24*60*60*1000).
EDIT: For those not understanding the problem, setDate receives a day number (1 to 31), and it's behaviour (though may work on some browsers) is not defined for other values. setTime works as expected.
http://www.w3schools.com/jsref/jsref_setDate.asp
精彩评论