How to Subtract Days from Date in JavaScript

JavaScript provides various methods to manipulate dates and times, and one of the common tasks is subtracting days from a date.

In this tutorial, we’ll discuss how to subtract days from a date in JavaScript, using both the native JavaScript methods and a popular library called moment.js.


Native JavaScript Methods

JavaScript provides two methods to work with dates: the Date object and the getTime() method.

The Date object allows you to create and work with dates in JavaScript.

To subtract days from a date in JavaScript, you need to create a new Date object and subtract the number of milliseconds in a day from it.

Here’s an example of subtracting 7 days from the current date:

let date = new Date();
let newDate = new Date(date.getTime() - 7 * 24 * 60 * 60 * 1000);
console.log(newDate);

In this example, we create a new Date object and store it in the date variable.

Then, we create another Date object newDate by subtracting the number of milliseconds in 7 days from the date object.

Finally, we log the new date to the console.

The getTime() method returns the number of milliseconds since January 1, 1970, and you can use this method to subtract days from a date.

Here’s an example:

let date = new Date();
let newDate = new Date(date.getTime() - 7 * 24 * 60 * 60 * 1000);
console.log(newDate);

In this example, we use the getTime() method to get the number of milliseconds since January 1, 1970, and subtract the number of milliseconds in 7 days from it.

Finally, we create a new Date object from the result and log it to the console.

moment.js Library

moment.js is a popular JavaScript library for working with dates and times, and it makes subtracting days from a date easy.

To use moment.js, you need to include it in your project, and then you can subtract days from a date like this:

let date = moment();
let newDate = date.subtract(7, 'days');
console.log(newDate.format('YYYY-MM-DD'));

In this example, we create a moment object from the current date and store it in the date variable.

Then, we subtract 7 days from the date object using the subtract() method, and store the result in the newDate variable.

Finally, we log the new date in the format of YYYY-MM-DD to the console.


Conclusion

Subtracting days from a date in JavaScript is a common task, and there are two ways to do it: using the native JavaScript methods or using a library like moment.js.

We’ve shown you both ways and provided code examples for each method, so you can choose the one that best fits your needs.