Scripts: Javascript :: Date and Time Functions :: Library Article #26
Developer's Section
Adding and Subtracting days to a Date Object in Javascript By: Erobo Team Member
Hire a Developer for Related Work / Installation | $55 hr
Rating: | Rate It:
Average Votes: (3316)
Favorites:
Learn a prototype method that can be used to create new date objects by adding / subtracting days to an existing date object.
In this tutorial you will learn a new Javascript prototype method that adds or subtracts days to a date object. This method will take as input a positive or negative integer number. When adding days you must enter a positive integer number, and a negative integer number when going back into the past. The object returned by this method can then be used to get the new resulting date object.
Example:
Add or subtract days to the date above:
The resulting date is:
Now Let's take a look at the Code Step by Step:
Create the prototype Date method: addDays(int value)
var targetDays = parseInt(s)
var thisYear = parseInt(this.getFullYear())
var thisDays = parseInt(this.getDate())
var thisMonth = parseInt(this.getMonth() + 1)
var currDays = thisDays;
var currMonth = thisMonth;
var currYear = thisYear;
var thisDate = new Date(currYear,currMonth - 1,monthDays)
return thisDate;
}
}
</script>
Create a simple set of inputs to test our prototype method:
Code Snippet 2
<input type="text" name="todaysDate" id="todaysDate" value=""> <br>
<script language="javascript">
//assign an initial date
var todaysDate = new Date()
document.getElementById("todaysDate").value = (todaysDate.getMonth() + 1) + "/" +
todaysDate.getDate() + "/" +
todaysDate.getFullYear();
</script>
Add or substract days to the date above:<br>
<input type="text" name="daysInput" id="daysInput" value="" size="3">
<input type="button" name="Add/Subtract" value="go"
onclick="
//get our initial date
var dateStr = document.getElementById('todaysDate').value
if(dateStr.length > 0 && dateStr.indexOf('/') != -1) {
var dateArr = dateStr.split('/')
if(dateArr.length == 3) {
//create a new date object with the initial date
var dateObj = new Date(dateArr[2],(dateArr[0] - 1), dateArr[1])
//call our new prototype method to add days to a date object
var newDate = dateObj.addDays(document.getElementById('daysInput').value)
//our newdate object will contain the result from our operation.
document.getElementById('resultingDate').value = (newDate.getMonth() + 1) + '/' +
newDate.getDate() + '/' +
newDate.getFullYear();
} else {
alert('The date entered is invalid')
}
}
"><br>
The resulting date is: <input type="text" name="resultingDate" id="resultingDate" value="">
Finally this prototype method can be very helpful. Especially when selecting date range for inputs on your forms!.