在JavaScript中获取两个日期之间的所有星期一的日期



我试图返回两个日期之间的所有星期一的日期。以下是我迄今为止所做的工作。

function populate_week_range_options(){
    var start_week_date = new Date(2012, 7-1, 2); // no queries exist before this
    //console.log(start_week_date);
    var todays_date = new Date();
    // array to hold week commencing dates
    var week_commencing_dates = new Array();
    week_commencing_dates.push(start_week_date);
    while(start_week_date < todays_date){
        var next_date = start_week_date.setDate(start_week_date.getDate() + 1);
        start_week_date = new Date(next_date);
        //console.log(start_week_date);
        if(start_week_date.getDay() == 1){
            week_commencing_dates.push(start_week_date);
        }
       //
    }
    return week_commencing_dates;
}
console.log(populate_week_range_options());

根据我在getDay()函数上阅读的文档,它返回一个表示一周中某一天(分别为0到6、周日到周六)的索引

然而,由于某种原因,我的函数改为周二返回——我不知道为什么!

我更改了if语句以将日期索引与0进行比较,这将返回我预期的日期,但我猜这是不正确的做法,因为0是周日的。

感谢您的帮助:-)

由于将元素推送到数组的方式,我似乎没有得到预期的日期。我更改了代码,以便它为要推送到数组的每个元素创建一个新的变量。我不是用JavaScript编码的,所以我不完全理解这一点,如果有人能解释这种行为,我将不胜感激。尽管如此,以下是我返回预期日期的更新代码:

function populate_week_range_options(){
    var start_week_date = new Date(2012, 7-1, 2); // no queries exist before this
    var todays_date = new Date();
    // array to hold week commencing dates
    var week_commencing_dates = new Array();
    var first_monday_date = new Date(2012, 7-1, 2); // no queries exist before this
    week_commencing_dates.push(first_monday_date);
    while(start_week_date < todays_date){
        var next_date = start_week_date.setDate(start_week_date.getDate() + 1);
        var next_days_date = new Date(next_date);
        day_index = next_days_date.getDay();
        if(day_index == 1){
            week_commencing_dates.push(next_days_date);
        }
        // increment the date
        start_week_date = new Date(next_date);
    }
    return week_commencing_dates;
}

getDay()根据本地时区返回日期。我假设您的日期从UTC时间转换为本地时间,并在您的计算机中设置偏移量,这将更改日期,从而更改一周中的哪一天。不过我真的不能在这里测试。

编辑:我认为您应该在这里使用getUTCDay()。

这真的很奇怪,我已经测试了你的代码,有趣的是,当我查看if Block内部和while循环(在数组中最后添加的元素上)时,它在console.log()中显示了星期一,但当我查看完整数组的末尾时(所以当几毫秒过去时),所有日期都是星期二。因此,大约1毫秒后,日期会发生变化。对不起,我没有给你答复,但我想提及这件事,这样其他人都会明白的。

最新更新