获取两个日期之间的所有日期,并仅返回该月的第一天

时间:2016-01-22 13:46:06

标签: javascript jquery

我有一些代码可以返回两个预定义日期之间的所有日期。这非常好,但我想知道如何只返回与月初相对应的值。

这样我得到了以下所需的结果:

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

我需要创建哪种方法才能让我分配本月的第一天。

2 个答案:

答案 0 :(得分:1)

您可以简单地构建一个新的Date对象,同时为其添加一个月。 以下是它的片段:

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

因此,currentDate选择上一个值的年份,在前一个值上添加一个月,并在构造新的Date对象时将日期设置为1(以确保您拥有第一天)。 通过使用这种方式,您可以防止不必要的循环(例如从1月份的第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>

答案 1 :(得分:1)

只需在你的while循环中替换:

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

per:

currentDate.setMonth(currentDate.getMonth() + 1);