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

Get all dates between two dates and return only the first of the month

本文关键字:日期 返回 第一天 两个 获取 之间      更新时间:2023-09-26

>我有一些代码可以返回两个预定义日期之间的所有日期。这非常好,但我想知道我怎么只能返回与每月第一天对应的值。

这样我就可以得到以下期望的结果:

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> '));
});

在这里演示

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

您可以

简单地构造一个新的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>

只需在 while 循环中替换:

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

每:

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