我在項目中使用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