【问题标题】:Getting an array of dates between start date and end date获取开始日期和结束日期之间的日期数组
【发布时间】:2015-10-06 12:00:29
【问题描述】:

我用 Javascript 编写的函数有问题。我正在尝试获取开始和结束之间的日期数组。

功能:

function getDateArray(startDate, endDate) {

    var dateArray = new Array(),
    currentDate = new Date(startDate),
    lastDay = new Date(endDate);
    while (currentDate <= lastDay) {
        if (!(currentDate.getUTCDay() === 0 || currentDate.getUTCDay() === 6)) {
            //currentDate.toUTCString(); //This line is redundant
            dateArray.push(currentDate);
        }
        currentDate.setDate(currentDate.getDate() + 1);
    }
    return dateArray;
}

每当我用两个日期调用这个函数时:

开始日期 = 2015 年 10 月 6 日 和结束日期 = 2015 年 10 月 12 日

我得到了不想要的结果:

Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)

如果有人可以向我强调这里有什么问题吗?

【问题讨论】:

  • currentDate.toUTCString(); 是空操作;你必须在某处分配结果。如果目标是推送字符串形式,则需要推送该值的返回。

标签: javascript date sharepoint-2013


【解决方案1】:

这是因为您每次都在推送对 currentDate 的引用(因为日期是复杂类型,它们是通过引用传递的)

只需替换这个:

dateArray.push(currentDate);

这样:

dateArray.push(new Date(currentDate));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多