我在项目中使用momentJS
,我有一个函数需要month
和year
,并使用这些参数返回月份的最后一天。瞬间JS月份的最后一天
一切工作正常,1至11月,并尽快,因为我用月,它返回月份。
任何想法,我可以调整这个工作?我传递真实的月份值(5 = 5月),然后在该函数中减去一个月,使其基于时刻才能正常运行。
小提琴: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())
完全是有道理的,没赶上那一个 - 谢谢! – SBB