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

后端 未结 7 2371
难免孤独
难免孤独 2021-01-04 12:39

Right now, I have this on my page:



        
7条回答
  •  粉色の甜心
    2021-01-04 13:30

    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:

    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.

    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.

提交回复
热议问题