2016-09-06 5 views
2

私はプロジェクトでmomentJSを使用していますが、私はmonthyearを受け取り、それらのパラメータを使用して月の最終日を返します。Moment JS月末の問題

すべてはうまく機能しています.1月から11月にかけて、12月を使用するとすぐに1月を返します。

どのように私はこれを動作させるために微調整できますか?真の月の値(5月= 5月)を渡してから、関数内で月を減算して、正しく機能するように瞬時に0にします。

フィドル: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-1]); 

基本的に、あなたは間違った時点で開始し、移動する必要はありません:

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

これを行ってくださいあなたは単に正しい点から始めたいと思っています。

+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>