Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 436
Steven Avatar asked Aug 18 '11 21:08

Steven


People also ask

How do you create an array of dates in Java?

Date [] dates = { new Date(), new Date() };

How do I find the date between two dates?

We can get the dates between two dates with single method call using the dedicated datesUntil method of a LocalDate class. The datesUntill returns the sequentially ordered Stream of dates starting from the date object whose method is called to the date given as method argument.


2 Answers

You could make use of setDate(getDate() + 1) to 'iterate' over all days: 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"));
like image 134
pimvdb Avatar answered Oct 05 '22 22:10

pimvdb


Here's a go: 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);
like image 21
Joe Avatar answered Oct 05 '22 23:10

Joe