Categories
JavaScript Answers

How to Get the First and Last Day of the Current Month with Moment.js?

Spread the love

Sometimes, we want to get the first and last day of the current month within our JavaScript app.

We can do this easily with moment.js.

In this article, we’ll look at how to get the first and last day of the current month with Moment.js.

Use the Moment.js startOf and endOf Methods

We can use the startOf method to get the first day of the current month.

And we can use the endOf method to get the last day of the current month.

For instance, we can write:

const startOfMonth = moment().clone().startOf('month').format('YYYY-MM-DD hh:mm');  
const endOfMonth = moment().clone().endOf('month').format('YYYY-MM-DD hh:mm');  
console.log(startOfMonth)  
console.log(endOfMonth)

We call moment to create a Moment object with the current date and time.

Then we call clone to clone that object.

Then we call startOf with 'month' to return the first day of the current month.

And then we call format to format the date into the human-readable YYYY-MM-DD format.

Likewise, we do the same with the endOf method to get the last day of the current month.

If the current month is April, 2021, then we should get:

'2021-04-01 12:00'

for startOfMonth .

And endOfMonth should be:

'2021-04-30 11:59'

startOf and endOf also accepts 'year' , 'week' , and 'day' as arguments to get the first and last year, week, or day of the given date and time.

Conclusion

We can get the first and last day of the current month easily with the Moment.js’s startOf and endOf methods respectively.

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 *