Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment JS start and end of given month

I need to calculate a JS date given year=2014 and month=9 (September 2014).

I tried this:

var moment = require('moment'); var startDate = moment( year+'-'+month+'-'+01 + ' 00:00:00' );             var endDate = startDate.endOf('month');             console.log(startDate.toDate());             console.log(endDate.toDate()); 

Both of logs show:

Tue Sep 30 2014 23:59:59 GMT+0200 (CEST) Tue Sep 30 2014 23:59:59 GMT+0200 (CEST) 

End date is correct but... why the start date is not?

like image 718
Fabio B. Avatar asked Sep 30 '14 22:09

Fabio B.


People also ask

How do you find the beginning of the month in a 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 moments with months?

The moment(). daysInMonth() function is used to get the number of days in month of a particular month in Node.


2 Answers

That's because endOf mutates the original value.

Relevant quote:

Mutates the original moment by setting it to the end of a unit of time.

Here's an example function that gives you the output you want:

function getMonthDateRange(year, month) {     var moment = require('moment');      // month in moment is 0 based, so 9 is actually october, subtract 1 to compensate     // array is 'year', 'month', 'day', etc     var startDate = moment([year, month - 1]);      // Clone the value before .endOf()     var endDate = moment(startDate).endOf('month');      // just for demonstration:     console.log(startDate.toDate());     console.log(endDate.toDate());      // make sure to call toDate() for plain JavaScript date type     return { start: startDate, end: endDate }; } 

References:

  • endOf()
  • clone()
  • Date from object
like image 102
klyd Avatar answered Sep 20 '22 09:09

klyd


you can use this directly for the end or start date of the month

new moment().startOf('month').format("YYYY-DD-MM"); new moment().endOf("month").format("YYYY-DD-MM"); 

you can change the format by defining a new format

like image 20
Shakti Jadon Avatar answered Sep 20 '22 09:09

Shakti Jadon