get all the dates that fall between two dates

后端 未结 2 1499
一整个雨季
一整个雨季 2020-12-15 01:59

i have a problem where the user selects a range of dates. i need to then find out what dates fall between those two selected dates. they\'re coming in via jquery with someth

相关标签:
2条回答
  • 2020-12-15 02:19
                //start of with getting the dates from your array 
                    var between =[]
                    for (var i = 0; i < arrayOfHolsInfoTbl.length; i++){
                        alert( holsInfoTblData[i].StartDate)
                        alert(holsInfoTblData[i].EndStart)
                        var datePickedStr1 = holsInfoTblData[i].StartDate;
                        var datePickedDate1 = new Date(datePickedStr1)//converts string to date object
    
                        var datePickedStr2 = holsInfoTblData[i].EndStart;
                        var datePickedDate2 = new Date(datePickedStr1)
    
                        while (datePickedDate1 <= datePickedDate2) {
                            between.push(new Date(datePickedDate1));
                            datePickedDate1.setDate(datePickedDate1.getDate() + 1);
                        }
                    }
                //loop through array and print  all dates that have been added to array 
                    for (var j = 0; j < between.length; j++) {
                        alert("This is all the dates " + between[j])
                    }
    
    0 讨论(0)
  • 2020-12-15 02:35

    You can grab the values from your date pickers using the getDate method, since this will return you a Date object. Then, starting at the start date increment "current" date by 1 day and add it to an array until the current date is the same as the end date.

    Note that you'll need to create a new Date() when adding it to the between array, or else you will just be referencing the currentDate object and all your values will be the same.

    Working Demo

    var start = $("#from").datepicker("getDate"),
        end = $("#to").datepicker("getDate"),
        currentDate = new Date(start.getTime()),
        between = []
    ;
    
    while (currentDate <= end) {
        between.push(new Date(currentDate));
        currentDate.setDate(currentDate.getDate() + 1);
    }
    
    0 讨论(0)
提交回复
热议问题