jQuery: handling booking calendars: solutions and techniques

jQuery: handling booking calendars: solutions and techniques

jQuery really kicks in when it comes to handle booking calendars.

jQuery really kicks in when it comes to handle booking calendars.

Future dates

The following function calculates a date in the future based on the number of days:


"use strict";

(function( $ ) {
  $.future = function( days ) {
    var dayMs = 86400000; // One day
    var timestamp = dayMs * days;
    var now = +new Date();
    var futureTs = now + timestamp;
    return new Date( futureTs );
  };
})( jQuery );

Filtering dates

How can we filter dates that for example fall into a specific weekday or not? The following function answers this question. You can optionally avoid using a future date by simply removing the first parameter. Remember that weekdays range from 0 to 6 in JavaScript.


"use strict";

(function( $ ) {

  $.filterDatesByDay = function( days, filterDay ) {
      var startDay = $.future( days ); // Or new Date() if you remove the 1st parameter
      var dayMs = 86400000;
      var dates = [];
      
      for( var i = 1; i <= 365; i++ ) {
          var day = dayMs * i;
          var start = startDay.getTime() + day;
          var nDate = new Date( start );
          if( nDate.getDay() !== parseInt( filterDay, 10 ) ) {
            var yy = nDate.getFullYear().toString();
            var mm = ( ( nDate.getMonth() + 1 ) < 10 ) ? '0' + ( nDate.getMonth() + 1 ).toString() : ( nDate.getMonth() + 1 ).toString();
            var dd = ( nDate.getDate() < 10 ) ? '0' + ( nDate.getDate() ).toString() : ( nDate.getDate() ).toString();
            var formattedDate = yy + "-" + mm + "-" + dd;
            dates.push( formattedDate );
          }
      }
      return dates;
  };

})( jQuery );

The above function can be further extended by allowing filtering on months, years and time using the same principle outlined earlier. Note that in the example the overall time span is one year (365 days) that can be extended or reduced as well.

Saving dates

To remember the choice made by users, you can use sessionStorage in order to survive page reloads or the simple switching between pages:


"use strict";

(function( $ ) {

  $(function() {
      $( "#date" ).datepicker({
        format: "yy-mm-dd"
      }).on( "changeDate", function( e ) {
          var date = e.date;
          sessionStorage.setItem( "my-date", date );
      });
  });

})( jQuery );