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

How to Easily Subtract Days from a Date in JavaScript?

DDD
Release: 2024-11-28 03:00:10
Original
1006 people have browsed it

How to Easily Subtract Days from a Date in JavaScript?

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);
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template