Categories
JavaScript Answers

How to Subtract Days from a JavaScript Date?

Spread the love

Subtract dates from a date is an operation that we’ve to do often in our JavaScript code.

In this article, we’ll look at how to subtract days from a JavaScript date.

Date.prototype.getDate and Date.prototype.setDate

We can use the getDate method to get the date.

And then use the setDate method to set the date by manipulating the date we got from getDate and passing the returned value into setDate .

For instance, we can write:

const date = new Date(2021, 1, 1);
date.setDate(date.getDate() - 5);
console.log(date)

to subtract 5 days from February 1, 2021.

We call getDate from the date object.

Then we subtract 5 days from it.

And then we pass that into setDate .

Therefore date is now 'Wed Jan 27 2021 00:00:00 GMT-0800 (Pacific Standard Time)’ .

date is changed in place with setDate .

Date.prototype.getTime and Date.prototype.setTime

We can also call setTime to set the timestamp of the date instead of the days.

This is more precise since the time is in milliseconds.

To do this, we write:

const dateOffset = (24 * 60 * 60 * 1000) * 5;
const date = new Date(2021, 1, 1);
date.setTime(date.getTime() - dateOffset);
console.log(date)

We have the dateOffset in milliseconds.

And we have the same date object as in the previous example.

In the 3rd line, we call setTime with the timestamp value returned from getTime , which is in milliseconds.

And we subtract that by dateOffset , which is 5 days in milliseconds.

date is changed in place with setTime .

So date in string form is now ‘Wed Jan 27 2021 00:00:00 GMT-0800 (Pacific Standard Time)' .

moment.js

We can use the moment.js library to make date manipulation easier.

For instance, we can write:

const dateMnsFive = moment('2021-02-01').subtract(5, 'day');
console.log(dateMnsFive.toDate())

We create a moment object for February 1, 2021 with moment .

The returned object has the subtract method to let us subtract the time amount we want.

The first argument is the amount.

And the 2nd argument is the unit of the amount to subtract from.

Then we can convert that back to a native JavaScript date object with toDate .

And so we get the same result as the previous examples.

Moment objects also come with the toISOString method.

For instance, we can write:

const dateMnsFive = moment('2021-02-01').subtract(5, 'day');
console.log(new Date(dateMnsFive.toISOString()))

We can pass in the string returned by toISOString to the Date constructor to get a native date object back.

And so we get the same result as the previous example.

Conclusion

We can subtract days from a date with native JavaScript date methods.

To make the work easier, we can also use a library like moment.js to help us.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.