我在项目中使用 momentJS
,我有一个函数接受 month
和 year
并返回该月的最后一天使用这些参数。
1 月到 11 月一切正常,我一使用 12 月,它就会在 1 月返回。
我有什么想法可以调整它来工作吗?我传递了真实的月份值(5 = 5 月),然后在函数中减去月份以使其基于 0,以便正确运行。
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())
最佳答案
代替:
var startDate = moment([year, month]).add(-1,"month");
这样做:
var startDate = moment([year, month-1]);
基本上,您不想从错误的点开始然后移动一个月,您只是想从正确的点开始。
关于javascript - Moment JS 每月最后一天问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39353993/