Home >Web Front-end >JS Tutorial >How to Subtract Days from a JavaScript Date to Get a Past Date?
Calculating Past Dates from a JavaScript Date
Finding the date some days prior to the current date is a common task in programming. This can be achieved effortlessly in JavaScript by manipulating the native Date object.
Question:
How can we subtract a specified number of days from a JavaScript Date to obtain a past date?
Answer:
The solution lies in utilizing the setDate() method of the Date object. This method takes the date value of the object and assigns a new one. To go back X days, we simply subtract X from the current date:
var d = new Date(); d.setDate(d.getDate() - 5);
Explanation:
In the above code, we create a Date object (d) representing the current date. Then, we call setDate() and subtract 5 from the existing date value, effectively moving back 5 days.
Note:
Example:
var d = new Date(); console.log('Today is: ' + d.toLocaleString()); d.setDate(d.getDate() - 5); console.log('5 days ago was: ' + d.toLocaleString());
This code will output the current date and the date 5 days prior to it.
The above is the detailed content of How to Subtract Days from a JavaScript Date to Get a Past Date?. For more information, please follow other related articles on the PHP Chinese website!