SBB SBB - 1 year ago 291
jQuery Question

Moment JS last day of month issue

I am using

in a project and I have a function that takes a
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.


// 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download