Simple Date Subtraction in JavaScript
Manipulating dates in JavaScript can be simple yet powerful. One common task is subtracting a specific number of days from a given date.
Method to Subtract Days from a Date
To reduce a Date object by a number of days, leverage the built-in setDate() method. It adjusts the date property of the Date object, effectively subtracting the specified number of days.
Code Example
The following code snippet demonstrates how to subtract 5 days from the current date:
var d = new Date(); d.setDate(d.getDate() - 5);
The code initializes a Date object, d, with the current date and time. The setDate() method then subtracts 5 days from the d object's date property. The date is modified in-place, and setDate() returns the updated date's time value.
Output
When executed, the provided code outputs:
Today is: Wednesday, February 8, 2023, 12:05:32 pm 5 days ago was: Friday, February 3, 2023, 12:05:32 pm
Notice that the date of the d object has been successfully reduced by 5 days.
The above is the detailed content of How to Easily Subtract Days from a Date in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!