2016-01-22 45 views
0

我有一些代碼返回兩個預定義日期之間的所有日期。這非常好,但我想知道如何才能返回與本月第一天相對應的值。獲取兩個日期之間的所有日期,並只返回本月的第一個

所以,我得到以下所需的結果:

Mon Feb 01 2016 01:00:00 GMT+0100 (W. Europe Standard Time) 
Tue Mar 01 2016 01:00:00 GMT+0100 (W. Europe Standard Time) 
Fri Apr 01 2016 01:00:00 GMT+0200 (W. Europe Daylight Time) 
Sun May 01 2016 01:00:00 GMT+0200 (W. Europe Daylight Time) 
Wed Jun 01 2016 01:00:00 GMT+0200 (W. Europe Daylight Time) 
Fri Jul 01 2016 01:00:00 GMT+0200 (W. Europe Daylight Time) 
Mon Aug 01 2016 01:00:00 GMT+0200 (W. Europe Daylight Time) 
Thu Sep 01 2016 01:00:00 GMT+0200 (W. Europe Daylight Time) 
Tue Nov 01 2016 01:00:00 GMT+0100 (W. Europe Standard Time) 

我的JS代碼:

$('#getBetween').on('click', function() { 
    var start = new Date("2016-01-01"), 
     end = new Date("2016-12-01"), 
     currentDate = new Date(start), 
     between = [] 
    ; 

    while (currentDate <= end) { 
     between.push(new Date(currentDate)); 
     currentDate.setDate(currentDate.getDate() + 1); 
    } 

    $('#results').html(between.join('<br> ')); 
}); 

DEMO HERE

我需要什麼樣的方法來創建它使我分配本月的第一個月。

回答

1

您可以簡單地構造一個新的Date對象,同時添加一個月。 這裏是它的一個片段:

currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1); 

所以currentDate採前值的年,月增加了先前的值,並設定一天爲1(以確保您有第一天)時構造一個新的Date對象。 通過使用這種方式,你會避免不必要的循環(如從第2天 - > 31月一月)

$('#getBetween').on('click', function() { 
 
    var start = new Date("2016-01-01"), 
 
     end = new Date("2016-12-01"), 
 
     currentDate = new Date(start), 
 
     between = [] 
 
    ; 
 

 
    while (currentDate <= end) { 
 
     between.push(new Date(currentDate)); 
 
     currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1); 
 
    } 
 
    
 
    $('#results').html(between.join('<br> ')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="getBetween">Get Between Dates</button> 
 
<div id="results"></div>

這工作也如果結束日期是不同的一年。

$('#getBetween').on('click', function() { 
 
    var start = new Date("2016-01-01"), 
 
     end = new Date("2017-06-01"), // end date is now mid 2017 
 
     currentDate = new Date(start), 
 
     between = [] 
 
    ; 
 

 
    while (currentDate <= end) { 
 
     between.push(new Date(currentDate)); 
 
     currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1); 
 
    } 
 
    
 
    $('#results').html(between.join('<br> ')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="getBetween">Get Between Dates</button> 
 
<div id="results"></div>

+0

謝謝你的反應和你解釋清楚。這正是我想要的。謝謝 – Rotan075

1

在while循環只需更換:

currentDate.setDate(currentDate.getDate() + 1); 

每:

currentDate.setMonth(currentDate.getMonth() + 1); 
相關問題