Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using moment.js to get number of days in current month

How would one use moment.js to get the number of days in the current month? Preferably without temporary variables.

like image 575
Michael Johansen Avatar asked Feb 22 '16 12:02

Michael Johansen


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 find day from moment date?

To get day name from date with Moment. js and JavaScript, we can use the format method. const myDate = "2022-06-28T00:00:00"; const weekDayName = moment(myDate).

What is Moment () hour ()?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().


2 Answers

Moment has a daysInMonth function:

Days in Month 1.5.0+

moment().daysInMonth(); 

Get the number of days in the current month.

moment("2012-02", "YYYY-MM").daysInMonth() // 29 moment("2012-01", "YYYY-MM").daysInMonth() // 31 
like image 118
T.J. Crowder Avatar answered Oct 20 '22 08:10

T.J. Crowder


You can get the days in an array

Array.from(Array(moment('2020-02').daysInMonth()).keys()) //=> [0, 1, 2, 3, 4, 5...27, 28]  Array.from(Array(moment('2020-02').daysInMonth()), (_, i) => i + 1) //=> [1, 2, 3, 4, 5...28, 29] 
like image 43
Shonubi Korede Avatar answered Oct 20 '22 09:10

Shonubi Korede