I have a form where a user can input a date in the format mm/dd/yyyy, and we need to add an 'expiration date' that is 30 days from the date entered, regardless of calendar month, leap years, or other complex calculations.

Thankfully, javascript already has the 'setDate()' function built in. We just have to parse the date object (a full javascript formatted date string) out of the given form input ( e.g. '11/10/2009').

Easy enough - first we parse out the numeric date/time object, and in this example, write it to the screen.

Then, we add 30 days (the number of days can be changed in the setting for the 'interval' variable - use a negative number to remove days)

Again, this example simply writes the date to the screen. In the current usage, I will use that date value to populate another text input in the same form as the initial date being entered.

view plain print about
1<script type="text/javascript">
2function setExpDate(formDate){
3    // set number of days to add
4    var interval = 30;
5    var startDate = new Date(Date.parse(formDate));
6    document.write('start: ' + startDate);
7    var expDate = startDate;
8    expDate.setDate(startDate.getDate() + interval);
9    document.write('<br>expire: ' + expDate);
10};
11</script>

Example usage on a form input:

view plain print about
1<input type="text" size="10" maxlength="10" id="startDate" name="startDate" onblur="setExpDate(this.value)">