2016-09-06 92 views
2

我在項目中使用momentJS,我有一個函數需要monthyear,並使用這些參數返回月份的最後一天。瞬間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()) 

回答

5

相反的:

var startDate = moment([year, month]).add(-1,"month"); 

這樣做:

var startDate = moment([year, month-1]); 

基本上,你不想在錯誤的點,然後移動到開始一個月後,你只需要從正確的角度開始。

+0

完全是有道理的,沒趕上那一個 - 謝謝! – SBB

1

您可以分析與格式的日期,然後瞬間就會正確地解析日期,而不需要在一個月中減去。我認爲這是更具可讀性到底

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>

相關問題