Do you need to have a delivery date setting for your Shopify store and need to be able to limit the date based on the time of the day and also make it a required field?
For example, if you run a bakery and want to stop delivery for orders after 1pm on the same day, then this code is for you.
To get started, you need to follow this official guide that should work on most themes, https://help.shopify.com/en/manual/online-store/themes/os/customize/add-date-picker.
Once you have that configured, you then want to adjust the code from <script> to </script> in the delivery-date.liquid to the below code.
You can also adjust the 780 in ((hour*60 + minutes) >= 780) to suit your preferred cut-off time, and for our North American counterparts, you might want to change dateFormat: ‘dd/mm/yy’, to something ridiculous like having the month appear before the day 😉
<script>
window.onload = function() {
if (window.jQuery) {
let $ = window.jQuery;
$(function() {
$( "#date" ).datepicker({
// Change date format to preferred style
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
// Set min date to today
minDate: "+0D",
// Set max date to 3 months past
maxDate: '+3M',
constrainInput: true
});
// Check time
var currentdate = new Date();
var hour = currentdate.getHours();
var minutes = currentdate.getMinutes();
// if time is after 13:00 (1pm) change allowed date to tomorrow.
if ((hour*60 + minutes) >= 780) {
currentdate.setDate(currentdate.getDate() + 1);
$( "#date" ).datepicker( "option", "minDate", currentdate);
}
});
}
}
</script>
Make the delivery date a required field
Some other neat functionality to also add is to make the date selector a required field.
First you need to add required to the input id in delivery-date.liquid
<input id="date" type="text" name="attributes[deliverydate]" value="{{ cart.attributes.deliverydate }}" required />
Then you want to edit your cart.liquid and search for
<form action="/cart" method="post" novalidate class="cart">
and then remove novalidate so it then becomes
<form action="/cart" method="post" class="cart">
Delivery date email notification
Lastly, but not least, don’t forget to add that delivery date to the customers (and shop owners) email notification by adding in: Delivery Date: {{ attributes.deliverydate }} in the emails. (located at www.yourstoreaddress/admin/settings/notifications)