0
votes

I'm attempting to create a booking calendar using the jQuery UI datepicker.

I want to be able to save all the dates in between a min and max range. Meaning, when the user selects a min date of "04/16/2014" and max date of "04/19/2014" I want to save every day in that range to an array.

Saving just the min and max date would probably not be enough, since there will be multiple min and max dates for all the different bookings.

This array will in turn be used to add a class to those dates as is shown in the code below.

    var bookedArray = <?php echo json_encode($bookedDates); ?>;

    // function putting dates into the calendar
    function bookedDates(mydate){
        var pickable=true;
        var displayClass ="available";
        var checkdate = $.datepicker.formatDate('mm/dd/yy', mydate);
        for(var i = 0; i < bookedArray.length; i++)
            {    
               if(bookedArray[i] == checkdate)
                  {
                pickable = true;
                displayClass= "booked-date";
                }
            }
        return [pickable,displayClass];
    }

    // jQuery UI calendar picker
    $( "#from" ).datepicker({
        beforeShowDay: bookedDates,
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 2,
        onClose: function( selectedDate ) {
            $( "#to" ).datepicker( "option", "minDate", selectedDate );
        }
    });
    $( "#to" ).datepicker({
        beforeShowDay: bookedDates,
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 2,
        onClose: function( selectedDate ) {
            $( "#from" ).datepicker( "option", "maxDate", selectedDate );
        }
    });
1

1 Answers

0
votes

You can traverse dates and add them to an array like this:

var bookedDays = [];

var date1 = new Date("04/19/2014");
var date2 = new Date("04/16/2014");

while(date1>=date2){
    bookedDays[bookedDays.length] =  getFullDate(date2); //append date to array
    date2.setDate(date2.getDate()+1); //increment by one day
}
console.log(bookedDays);

Following function adapted from: How do I get the current date in JavaScript?

function getFullDate(dateObj){

    var dd = dateObj.getDate();
    var mm = dateObj.getMonth()+1; //January is 0!
    var yyyy = dateObj.getFullYear();

    if(dd<10) {
        dd='0'+dd
    } 

    if(mm<10) {
        mm='0'+mm
    } 

    return mm+'/'+dd+'/'+yyyy;

}