Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sworup/30b7189d1ac5e478787b to your computer and use it in GitHub Desktop.
Save sworup/30b7189d1ac5e478787b to your computer and use it in GitHub Desktop.
Datepicker Initializer (PHP) (jQuery) (jQuery UI) (Datepicker)
<?php
function createDateRangeArray($strDateFrom,$strDateTo)
{
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange=array();
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
// Create a daterange array
$all_availability_date = $wpdb->get_results('SELECT DISTINCT(from_date), to_date FROM '.$table_name, ARRAY_A);
$dateSet = array();
foreach ($all_availability_date as $key => $dateRange) {
$dateSet = array_merge($dateSet, createDateRangeArray($dateRange['from_date'],$dateRange['to_date']));
}
<input type="hidden" name="date_ranges" value="<?php echo htmlentities(json_encode($dateSet)) ?>">
// Disable a certain date range. Minimum Date today. Constrain Input. 'From' and 'to' datepicker set.
$(function() {
disabledDays = jQuery.parseJSON($('input:hidden[name=date_ranges]').val());
$( "#from" ).datepicker({
dateFormat: "yy-mm-dd",
defaultDate: "+1w",
changeMonth: true,
minDate: 0,
constrainInput: true,
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [$.inArray(string, disabledDays) == -1];
},
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#to" ).datepicker({
dateFormat: "yy-mm-dd",
defaultDate: "+1w",
changeMonth: true,
minDate: 0,
constrainInput: true,
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [$.inArray(string, disabledDays) == -1];
},
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment