SBB SBB - 3 months ago 49
jQuery Question

Moment JS last day of month issue

I am using

momentJS
in a project and I have a function that takes a
month
and
year
and returns the last day of the month using those parameters.

Everything is working fine, Jan - November, and as soon as I use December, it is returning January.

Any ideas how I can tweak this to work? I am passing the true month value (5 = May) and then subtracting a month within the function to make it 0 based for moment to function correctly.

Fiddle: https://jsfiddle.net/bhhcp4cb/

// Given a year and month, return the last day of that month
function getMonthDateRange(year, month) {

// 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]).add(-1,"month");

// Clone the value before .endOf()
var endDate = moment(startDate).endOf('month');

// make sure to call toDate() for plain JavaScript date type
return { start: startDate, end: endDate };
}

// Should be December 2016
console.log(moment(getMonthDateRange(2016, 12).end).toDate())

// Works fine with November
console.log(moment(getMonthDateRange(2016, 11).end).toDate())

Answer

Instead of:

var startDate = moment([year, month]).add(-1,"month");

Do this:

var startDate = moment([year, month-1]);

Basically, you don't want to start at the wrong point and then move by a month, you simply want to start at the correct point.