Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment js get first and last day of current month

People also ask

How do you find the first day of the current month in this moment?

Use the Moment.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.

How do you compare two dates in a moment?

We can use the isAfter method to check if one date is after another. We create a moment object with a date string. Then we call isAfter on it with another date string and the unit to compare.


In case anyone missed the comments on the original question, you can use built-in methods (works as of Moment 1.7):

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

There would be another way to do this:

var begin = moment().format("YYYY-MM-01");
var end = moment().format("YYYY-MM-") + moment().daysInMonth();

You can do this without moment.js

A way to do this in native Javascript code :

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

firstDay = moment(firstDay).format(yourFormat);
lastDay = moment(lastDay).format(yourFormat);

moment startOf() and endOf() is the answer you are searching for.. For Example:-

moment().startOf('year');    // set to January 1st, 12:00 am this year
moment().startOf('month');   // set to the first of this month, 12:00 am
moment().startOf('week');    // set to the first day of this week, 12:00 am
moment().startOf('day');     // set to 12:00 am today