JavaScript Date Manipulation: Adding Days to a Date
In JavaScript, adding days to a Date object can be achieved using a custom function. While .NET offers a built-in AddDay() method, JavaScript does not.
Custom Function for Adding Days
To create a function for adding days to a Date object, you can utilize the following code:
Date.prototype.addDays = function(days) { var date = new Date(this.valueOf()); date.setDate(date.getDate() + days); return date; };
This function extends the Date object's prototype with an addDays() method, which accepts the number of days to add. It creates a new Date object by cloning the original date, then modifies the date value by the specified number of days.
Usage
To use the custom addDays() method, you can simply call it on a Date object:
var date = new Date(); console.log(date.addDays(5));
This will output a new Date object that is 5 days later than the original date.
The above is the detailed content of How Can I Add Days to a JavaScript Date Object?. For more information, please follow other related articles on the PHP Chinese website!