Categories
JavaScript Answers

How to Get Tomorrow, Today, and Yesterday’s Date with Moment.js?

Spread the love

We can get today’s date with the moment function.

And then we can format it into a human-readable date string with the format method.

For instance, we can write:

const today = moment();
console.log(today.format('YYYY-MM-DD'))

to create the today variable that’s set to a moment object with today’s date.

And then we call format with 'YYYY-MM-DD' to format the date to YYYY-MM-DD format.

Get Tomorrow’s Date

We can get tomorrow’s date with the moment function and the add method.

And then we can format it into a human-readable date string with the format method.

For instance, we can write:

const tomorrow = moment().add(1, 'days');
console.log(tomorrow.format('YYYY-MM-DD'))

to create the tomorrow variable that’s set to a moment object with today’s date.

Then we call add with 1 and 'days' to add one day to today.

And then we call format with 'YYYY-MM-DD' to format the date to YYYY-MM-DD format.

Get Yesterday’s Date

We can get tomorrow’s date with the moment function and the add method.

And then we can format it into a human-readable date string with the format method.

For instance, we can write:

const yesterday = moment().add(-1, 'days');
console.log(yesterday.format('YYYY-MM-DD'))

to create the tomorrow variable that’s set to a moment object with today’s date.

Then we call add with -1 and 'days' to subtract one day to today.

And then we call format with 'YYYY-MM-DD' to format the date to YYYY-MM-DD format.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *