SBB
SBB

Reputation: 8970

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())

Upvotes: 2

Views: 2231

Answers (2)

baao
baao

Reputation: 73231

You can parse the date with a format, then moment will parse the date correctly without the need of subtracting a month. I think it's more readable in the end

var startDate = moment(year + "" + month, "YYYYMM");
var endDate = startDate.endOf('month');

// Given a year and month, return the last day of that month
function getMonthDateRange(year, month) {
    var startDate = moment(year + "" + month, "YYYYMM");
    var endDate = 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())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment-with-locales.min.js"></script>

Upvotes: 1

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241485

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.

Upvotes: 5

Related Questions