Skip to content

Instantly share code, notes, and snippets.

@icodejs
Created April 23, 2012 08:23
Show Gist options
  • Save icodejs/2469494 to your computer and use it in GitHub Desktop.
Save icodejs/2469494 to your computer and use it in GitHub Desktop.
JQ UI Date picker - Force users to choose a delivery date in the future and take into account weekends
function days_between(date1, date2) {
var one_day = 1000 * 60 * 60 * 24,
date1_ms = date1.getTime(),
date2_ms = date2.getTime(),
difference_ms = Math.abs(date1_ms - date2_ms);
return Math.round(difference_ms / one_day);
}
function disable_specific_days(date) {
var now = new Date(),
arr = [],
disable_monday = false,
is_weekend = (now.getDay() === 0 || now.getDay() === 6),
no_of_delivery_days = is_weekend ? 2 : 1,
dp_date_is_weekend = (date.getDay() === 0 || date.getDay() === 6),
is_friday = (now.getDay() === 5),
date_in_the_past = (date.getTime() - now.getTime()) < 0,
past_2_pm = (now.getHours() >= 14),
dp_is_today = (date.toDateString() === now.toDateString()),
days_between_dates = (function(days) {
return past_2_pm ? days -1 : days; // 1 days grace for delivery unless after 2pm (then remove 1 day)
}(days_between(now, date)));
disable_monday = (function() {
if (is_weekend) { // only used when hitting this page on a weekend
return (date.getDay() === 1 && days_between_dates < 4); // if weekend dont disable all mondays. Just the next one
} else if (is_friday) { // only used when hitting this page on a friday
return (date.getDay() === 1 && days_between_dates < 4 && past_2_pm); // if less than 4 days until the closet monday and after 2pm? then disable all mondays.
}
}());
var disable_date = disable_monday ||
dp_date_is_weekend ||
(days_between_dates < no_of_delivery_days) ||
(days_between_dates <= no_of_delivery_days && past_2_pm && is_friday) ||
date_in_the_past,
enable_date = !disable_date; // duhhhh!
arr.push(enable_date);
arr.push("");
return arr;
}
$(function() {
var $delivery_date = $("#delivery_date");
$delivery_date.datepicker({
dateFormat:'dd-mm-yy',
numberOfMonths: 2,
showOn: "button",
beforeShowDay: disable_specific_days // http://docs.jquery.com/UI/Datepicker#event-beforeShowDay
});
(function() {
// set the value of the delivery_date textbox to the first available date. If a delivery date has been
// chosen previously, (i.e. user comes back to the page to amend details) do nothing.
var prepopulate_delivery_date = <%= cstr(cbool(GlobalRegistry.OrderInProgress.DeliveryDate < now)).toLower() %>,
dateIsDeliverable,
initialDate = new Date();
if (prepopulate_delivery_date) {
do {
dateIsDeliverable = disable_specific_days(initialDate)[0];
if (!dateIsDeliverable) {
initialDate.setDate(initialDate.getDate() + 1);
} else {
$delivery_date.val(initialDate.toCSDate());
}
} while (!dateIsDeliverable);
}
}());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment