Javascript 给定开始日期和结束日期,创建两个日期之间的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7114152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:54:10  来源:igfitidea点击:

Given a start and end date, create an array of the dates between the two

javascriptjquery

提问by Steven

Right now, I have this on my page:

现在,我的页面上有这个:

<script type="text/javascript">
    $(document).ready(function () {
        var days = [
            { Date: new Date($('#hfEventStartDate').val()) },
            { Date: new Date($('#hfEventEndDate').val()) }
        ];
    });
</script>

<asp:HiddenField ID="hfEventStartDate" runat="server" />
<asp:HiddenField ID="hfEventEndDate" runat="server" />

I'm setting hfEventStartDate and hfEventEndDate when the page loads. With my code right now, it creates an array with two values: the start date and the end date. But I'd like to also have the array contain all the dates in between. How can I do that?

我在页面加载时设置 hfEventStartDate 和 hfEventEndDate。使用我现在的代码,它会创建一个包含两个值的数组:开始日期和结束日期。但我还想让数组包含两者之间的所有日期。我怎样才能做到这一点?

回答by pimvdb

You could make use of setDate(getDate() + 1)to 'iterate' over all days: http://jsfiddle.net/pimvdb/4GeFD/1/.

你可以setDate(getDate() + 1)在所有日子里“迭代”:http: //jsfiddle.net/pimvdb/4GeFD/1/

$("#hfEventStartDate").val(new Date - 24 * 3600 * 1000 * 7 - 1);
$("#hfEventEndDate").val(new Date - 0);

function getAllDays() {
    var s = new Date($('#hfEventStartDate').val() - 0);
    var e = new Date($('#hfEventEndDate').val() - 0);
    var a = [];

    while(s < e) {
        a.push(s);
        s = new Date(s.setDate(
            s.getDate() + 1
        ))
    }

    return a;
};

alert(getAllDays().join("\n"));

回答by Joe

Here's a go: jsFiddle

来吧jsFiddle

var date1 = new Date();
var date2 = new Date(2010, 0, 1);
var day;
var between = [date1];

while(date2 <= date1) {
    day = date1.getDate()
    date1 = new Date(date1.setDate(--day));  
    between.push(date1);
}

console.log(between);

回答by Michal

        start = new Date("August 13,2011");
        future = new Date("October 13, 2011");
        range = []
        mil = 86400000 //24h
        for (var i=start.getTime(); i<future.getTime();i=i+mil) {

          range.push(new Date(i))

       //or for timestamp
       //range.push(i)
        }

回答by Ahmed Aswani

try momment.jsand twix

尝试momment.jstwix

var itr = moment.twix(new Date('2012-01-15'),new Date('2012-01-20')).iterate("days");
var range=[];
while(itr.hasNext()){
    range.push(itr.next().toDate())
}
console.log(range);

live:http://jsfiddle.net/aswani/GNPQc/

直播:http: //jsfiddle.net/aswani/GNPQc/

回答by Xspirits

I have read the given answer and this is what I came out with. Note that I started from the answer of @pimvdb

我已经阅读了给定的答案,这就是我得出的结论。请注意,我从@pimvdb 的回答开始

// return an array composed of a list of the days' number 
// from 1 month ago until today, not included
function getAllDays() {
 var e = moment();
 var s = moment().subtract('months', 1);
 var a = []
  // While the updated start date is older, perform the loop.
  while(s.isBefore(e)) {
   // Update the format according to moment js documentations format().
   a.push(s.format("MMM - DD"));
   s = s.add('days', 1);
  }
 return a;
}

Simply call the function anywhere in your code:

只需在代码中的任何位置调用该函数:

getAllDays();

see also: MomentJs library

另见:MomentJs 库

回答by Theswolf

You can also use an interval to do what you want.

您还可以使用间隔来做您想做的事情。

var tstamp = 0;


function timer() {

    console.log(tstamp);
    tstamp = new Date().getTime()
}

var i = setInterval(timer, 1000);

//when no more needed
clearInterval(i)

回答by user2734756

This worked for me too:

这对我也有用:

$("#hfEventStartDate").val(new Date - 24 * 3600 * 1000 * 7 - 1);
$("#hfEventEndDate").val(new Date - 0);

function getAllDays() {
    var s = new Date($('#hfEventStartDate').val() - 0);
    var e = new Date($('#hfEventEndDate').val() - 0);
    var a = [];
    while(s <= e) {
        a.push(new Date(s));
        s.setDate(s.getDate() + 1);
    }

    return a;
};

alert(getAllDays().join("\n"));

Is the same code that pimvdb published with some minor changes, but it gives a different result. It took me 4 hours trying to understand why, and this is what i think happens with pimvdb code:

与 pimvdb 发布的代码相同,但做了一些小改动,但给出了不同的结果。我花了 4 个小时试图理解原因,这就是我认为 pimvdb 代码会发生的情况:

1 loop
a[0] = S1 = $("#hfEventStartDate").val(new Date - 24 * 3600 * 1000 * 7 - 1);
//2013-09-01

2 loop
a[0] = s1.setDate(s1.getDate() + 1); // 2013-09-02
a[1] = s2 = new Date(s1.setDate(s1.getDate() + 1)) // 2013-09-02

3 loop
a[0] = s1; // 2013-09-02
a[1] = s2.setDate(s2.getDate() + 1); // 2013-09-03
a[2] = s3 = new Date(s2.setDate(s2.getDate() + 1)) // 2013-09-03

and so on...

I'm not sure if this was deliberately intended by pimvdb but his code lefts out the starting day, which in my example would be 2013-09-01. But even if it was intended, why not leaving out the last day as well? at least that's what while(s < e) seemed intended for, but the last day is included in the final array.

我不确定这是否是 pimvdb 有意为之,但他的代码忽略了起始日,在我的示例中为 2013-09-01。但即使是有意为之,为什么不把最后一天也去掉呢?至少这就是 while(s < e) 的目的,但最后一天包含在最终数组中。

I'm sorry I may be wrong, I have never worked with object orientated programing, but trying to understand why a[0] was getting changed on the second loop after already been assigned on the fist one made me absolutely insane. Hope I'm not so wrong. Thank you.

对不起,我可能是错的,我从来没有使用过面向对象的编程,但是试图理解为什么 a[0] 在已经被分配到第一个循环之后在第二个循环中被改变让我绝对疯了。希望我没有错。谢谢你。