Home >Web Front-end >JS Tutorial >How to Subtract Days from a JavaScript Date to Get a Past Date?

How to Subtract Days from a JavaScript Date to Get a Past Date?

DDD
DDDOriginal
2024-12-04 12:14:11603browse

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:

  • This method modifies the date object itself. If you prefer an immutable alternative, create a new Date object instead of modifying the existing one.
  • The setDate() method returns the updated date's time value.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn