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?
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.
The moment(). daysInMonth() function is used to get the number of days in month of a particular month in Node.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With