Subtracting Days from a JavaScript Date
Calculating past dates based on a given JavaScript Date object can be a common requirement. For instance, you may need to determine the date that occurred a certain number of days prior to the current date.
To achieve this, you can utilize the setDate method of the Date object. This method accepts a numeric value that represents the day of the month you want to set the date to.
Example:
Let's suppose you want to calculate the date that occurred 5 days before today. You can do this as follows:
var d = new Date(); d.setDate(d.getDate() - 5);
In this example, we create a new Date object d representing the current date. Then, we use the setDate method to subtract 5 days from the current date. This updates the d object to hold the date that occurred 5 days in the past.
Note:
It's important to remember that the setDate method modifies the Date object itself. If you need to preserve the original date, consider creating a copy of the Date object before modifying it.
The above is the detailed content of How Can I Subtract Days from a JavaScript Date?. For more information, please follow other related articles on the PHP Chinese website!