Disable weekends, all holidays and Mondays in pure JavaScript date picker - javascript

In a Shopify project running Booster theme, we're not using jQuery at all. So I'm using a simple plug-in to add the date-picker in the cart page. With the below code, I've only been able to just get the date-picker working, but I'm not sure how to disable weekends, all holidays and Mondays?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Date Picker</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="dtsel.css" />
<script src="dtsel.js"></script>
</head>
<body>
<input name="dateTimePicker" />
</body>
<script>
instance = new dtsel.DTS('input[name="dateTimePicker"]');
instance = new dtsel.DTS('input[name="dateTimePicker"]', {
showTime: true
});
instance = new dtsel.DTS('input[name="dateTimePicker"]', {
showTime: true,
showDate: false
});
instance = new dtsel.DTS('input[name="dateTimePicker"]', {
dateFormat: "yyyy-mm-dd",
timeFormat: "HH:MM:SS"
});
instance = new dtsel.DTS('input[name="dateTimePicker"]', {
direction: 'BOTTOM'
});
instance = new dtsel.DTS('input[name="dateTimePicker"]', {
defaultView: "MONTHS"
});
instance = new dtsel.DTS('input[name="dateTimePicker"]', {
paddingX: 5,
paddingY: 5
});
</script>
</html>
Links to the plug-in site and github repository are below.
https://www.cssscript.com/date-time-picker-dtsel/
https://github.com/crossxcell99/dtsel
Could you please help get the JavaScript code above do exactly what the jQuery code below does?
<script>
jQuery(document).ready( function() {
jQuery(function() {
var disabledDays = ["2021-12-23","2021-12-24","2021-12-30","2021-12-25", "2021-12-31", "2021-1-1"];
var myDate = new Date();
if (myDate.getDay() == 5) {
// If today is Friday, disallow the Monday of the coming week (3 days later)
myDate.setDate(myDate.getDate() + 3);
disabledDays.push(jQuery.datepicker.formatDate('yy-m-d', myDate));
}
jQuery("#ship_date").datepicker({
minDate: +2,
maxDate: '+2M',
beforeShowDay: function(date) {
var day = date.getDay();
var string = jQuery.datepicker.formatDate('yy-m-d', date);
var isDisabled = ($.inArray(string, disabledDays) != -1);
//day != 0 and day != 6 disable weekends
return [day != 0 && day != 6 && !isDisabled];
}
});
});
});
</script>

You can have a look at VanillaJS DatePicker. It has all your required options and is completely written in JavaScript with no external dependencies. In the below code, you can see a minimal example of conditions that you stated in your question.
daysOfWeekDisabled - 0 and 6 disables Sunday and Saturday
datesDisabled - Dates to disable including next Monday if it is Friday today
minDate - Minimum Date that can be picked is +2days
maxDate - Maximum Date that can be picked is +60days
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
const DISABLED_DATES = ['03/11/2022'];
const today = new Date();
if(today.getDay() === 5){
DISABLED_DATES.push(addDays(today, 3));
}
const elem = document.querySelector('#foo');
const datepicker = new Datepicker(elem, {
pickLevel: 0,
daysOfWeekDisabled: [0,6],
datesDisabled: DISABLED_DATES,
minDate: addDays(today, 2),
maxDate: addDays(today, 60)
});
<link href="https://cdn.jsdelivr.net/npm/vanillajs-datepicker#1.2.0/dist/css/datepicker.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/vanillajs-datepicker#1.2.0/dist/js/datepicker.min.js"></script>
<div id="foo"></div>
Add days code is from here.
I have intentionally added 60 days instead of 2 months. You will need to fix this to get accurate maxDate.

Related

How to set dynamic parameters value in jqueryUI widgets plugin "Multi-date-picker"

I tried to make a multi date selector calendar with jqueryUI and came to know about a plugin named "Multi-Dates-Picker". The problem with that is that I could not dynamically set the value in the usual way of a setter method in jqueryUI widgets, while the getter method works fine.
var date = new Date();
var today = new Date();
var tomorrow = (new Date()).setDate(today.getDate() + 1);
function myFunction() {
$('#mdp-demo').multiDatesPicker({
minDate: 3, // today
maxDate: 15, // +30 days from today
maxPicks: 2,
});
}
function maxpicksup() {
// Setter
$("#mdp-demo").datepicker("option", "maxDate", 21);
$("#mdp-demo").datepicker("option", "minDate", 0);
//setter
$("#mdp-demo").datepicker("option", "maxPicks", 5);
// Getter
var firstDay = $("#mdp-demo").datepicker("option", "maxPicks");
alert(firstDay);
}
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-ui-multidatespicker#1.6.6/jquery-ui.multidatespicker.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-ui-multidatespicker#1.6.6/jquery-ui.multidatespicker.js"></script>
<body onload="myFunction()">
<div class="" id="mdp-demo"></div>
<button onclick="maxpicksup()">click</button>
</body>

Check date range in Jquery Datepicker

So i'm having the following code of a jquery datepicker
$(".dateInput").datepicker({
language:"el",
format: " dd/mm/yyyy",
startView: "+0d",
todayHighlight: true,
autoclose: true,
onClose: function() {
.........
}
})
and i would like to do a check on the onClose, where, if the date that the user selects is one month before the today date or one year after, an alert message would appear.
Any suggestions are really appreciated.
Thank you in advance.
Welcome to StackOverflow,
here is possible solution for your request:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
$(".dateInput").datepicker({
language: "el",
format: "dd/mm/yyyy",
startView: "+0d",
todayHighlight: true,
autoclose: true,
onClose: function(dateText, inst) {
var date = new Date(dateText);
var dateMin = new Date();
dateMin.setMonth(dateMin.getMonth() - 1);
dateMin.setHours(0, 0, 0, 0); // Set time to the beginning of the day
var dateMax = new Date();
dateMax.setFullYear(dateMax.getFullYear() + 1);
dateMax.setHours(23, 59, 59, 999); // Set time to the end of the day
if (date >= dateMin && date <= dateMax) {
alert("Date is in range.");
} else {
alert("Date is NOT in range.");
}
}
});
});
</script>
</head>
<body>
<p>Date: <input type="text" class="dateInput"></p>
</body>
</html>
You can find more info about Date object on MDN.

Fetch today date and add 7 days (for Google Opt-In code)

I don't know Javascript or PHP and I've tried my best finding an answer online but without the basic knowledge I have no clue how to do this. I am sure there are many people like me who are stuck.
My situation is that I need to insert a delivery date by somehow fetching the current date and adding 7 days to it, then input it to the "YYYY-MM-DD" field in the code below.
The best answer I've found is here but I have no clue how to implement it
This is the full code, please help me figure out how to structure it:
<!-- BEGIN GCR Opt-in Module Code -->
<script src="https://apis.google.com/js/platform.js?onload=renderOptIn"
async defer>
</script>
<script>
window.renderOptIn = function() {
window.gapi.load('surveyoptin', function() {
window.gapi.surveyoptin.render(
{
// REQUIRED
"merchant_id":"xxxxxxxxxx",
"order_id": "{BOOKINGNUMBER}",
"email": "{EMAIL}",
"delivery_country": "ISO 3166-2:CA",
"estimated_delivery_date": "YYYY-MM-DD",
// OPTIONAL
"opt_in_style": "CENTER_DIALOG"
});
});
}
</script>
<!-- END GCR Opt-in Module Code -->
sevenDaysFromNow will get the current date and time, then I will set it to current date and time + 7 days.
You can read about setDate / getDate here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate
Then I am using formatDate function to convert it to yyyy-mm-dd.
Conversion date format was taken from here
Format JavaScript Date to yyyy-mm-dd
This is the result:
<!-- BEGIN GCR Opt-in Module Code -->
<script src="https://apis.google.com/js/platform.js?onload=renderOptIn"
async defer>
</script>
<script>
var sevenDaysFromNow = new Date().setDate(new Date().getDate() + 7);
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
window.renderOptIn = function() {
window.gapi.load('surveyoptin', function() {
window.gapi.surveyoptin.render(
{
// REQUIRED
"merchant_id":"xxxxxxxxxx",
"order_id": "{BOOKINGNUMBER}",
"email": "{EMAIL}",
"delivery_country": "ISO 3166-2:CA",
"estimated_delivery_date": formatDate(sevenDaysFromNow),
// OPTIONAL
"opt_in_style": "CENTER_DIALOG"
});
});
}
</script>
<!-- END GCR Opt-in Module Code -->

how to dynamically disable specific date in jquery datepicker?

I am trying to dynamically disable date (jquery datepicker) which is already in database. I have done static method in that I am able to achieve goal but not getting success in dynamic approach
<script language="javascript">
$(document).ready(function () {
var getfromdb = #Html.Raw(#ViewBag.bookdate);
var result = '\'' + getfromdb.toString().split(',').join('\',\'') + '\'';
var disableddates = [result];
var newdisableddates = ['17/10/2017','18/10/2017','19/10/2017','22/10/2017','23/10/2017','24/10/2017','25/10/2017']; // Static Approach
$("#txtFromdate").datepicker({
minDate: 0,
beforeShowDay: DisableSpecificDates,
dateFormat: 'dd/mm/yy'
});
$("#txtTodate").datepicker({
minDate: 0,
beforeShowDay: DisableSpecificDates,
dateFormat: 'dd/mm/yy'
});
function DisableSpecificDates(date) {
var string = jQuery.datepicker.formatDate('dd/mm/yy', date);
return [disableddates.indexOf(string) == -1];
}
});
And here is my controller code:
List<string> getbookdate = new List<string>();
getbookdate = BookDate(id);
ViewBag.bookdate = JsonConvert.SerializeObject(getbookdate.ToList());
public List<string> BookDate(int? id)
{
DateTime dt = System.DateTime.Now.Date;
var getbookdate = (from x in entity.BookingMasters
join
y in entity.BookingDetails on x.BookingId equals y.BookingId
where x.ProductId == id && y.FromDate > dt && y.ToDate > dt
select new BookingModel { ProductId = x.ProductId.Value, FromDate = y.FromDate.Value, ToDate = y.ToDate.Value }).ToList();
List<string> allDates = new List<string>();
foreach (var r in getbookdate)
{
for (DateTime date = r.FromDate; date <= r.ToDate; date = date.AddDays(1))
{
allDates.Add(Convert.ToString(date.ToShortDateString()));
}
}
return allDates;
}
Disable doesn't work well with date picker. Try my plnkr.
https://embed.plnkr.co/h4RaeIKJVfj9IjyHREqZ/
It gets the datepicker on click and parses through the dates and data set given and if a match is found it removes the click event on it. and repeats on each render please see my plnkr link for html. Hope it helps
<!--Disable doesn't work well with date picker. Try this. Hope it helps-->
<!--Working example https://embed.plnkr.co/h4RaeIKJVfj9IjyHREqZ/ -->
<!--Code-->
<!--HTML PART-->
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script data-require="tether#*" data-semver="1.4.0" src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<link data-require="bootstrap#4.0.5" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
<link data-require="jqueryui#*" data-semver="1.12.1" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<script data-require="jqueryui#*" data-semver="1.12.1" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
</head>
<body class="container">
<h1>Hello User</h1>
<div class="box">
<div class="box-content">
<div class="row">
<div class="col-md-4">
<label>Date:</label>
<input type="text" id="date-picker-control" />
</div>
</div>
</div>
</div>
<script>
var element = $('#date-picker-control');
element.datepicker();
element.off('click').on('click', function() {
// Setup DatePicker
console.log('Update Date Picker');
// If user changes month or year, update date picker
// based on the date list you have
$("#ui-datepicker-div")
.find("div.ui-datepicker-header")
.find('a.ui-datepicker-next, a.ui-datepicker-prev')
.on('click', function() {
element.click();
});
// Get all available dates in current displayed dates
var availableDates = $("#ui-datepicker-div")
.find("table.ui-datepicker-calendar")
.find('td[data-handler="selectDay"]');
availableDates.filter(function(i) {
var targetDateElement = $(this);
//Get date parts
var year = +targetDateElement.data("year");
var month = targetDateElement.data("month") + 1; //JS fix
var day = +targetDateElement.find('a.ui-state-default').text();
var builtDate = month + '/' + day + '/' + year;
// you can substitute your json data
var targetDates = [
"10/2/2017", "10/6/2017", "10/8/2017"
];
$.each(targetDates, function(i, targetDate) {
// If builtDate match targetdate then turn click event oFF on that date
if (targetDate == builtDate) {
targetDateElement.css({
'border': '1px solid gray',
'background': 'darkgray',
'font-weight': 'bold',
'color': 'gray'
}).off('click');
}
});
});
});
</script>
</body>
</html>
Your original idea is in the right direction, but I think there's probably something weird going on with all the string conversion. I'd just pass through dates and compare with dates rather than all the stringy stuff:
I've written this quick test...
controller:
//Replace with however you get dates
ViewBag.DatesList = new List<DateTime>()
{
new DateTime(2018, 01, 01),
new DateTime(2018, 01, 02),
new DateTime(2018, 01, 03)
};
return View();
View:
<script language="javascript">
$(document).ready(function () {
var disableddates = [];
#foreach (DateTime date in ViewBag.DatesList)
{
//note JS month is zero-based for no good reason at all...
#:disableddates.push(new Date(#date.Year, #date.Month-1, #date.Day))
}
$("#txtFromdate").datepicker({
minDate: 0,
beforeShowDay: DisableSpecificDates,
dateFormat: 'dd/mm/yy'
});
$("#txtTodate").datepicker({
minDate: 0,
beforeShowDay: DisableSpecificDates,
dateFormat: 'dd/mm/yy'
});
function DisableSpecificDates(date) {
//filter array to find any elements which have the date in.
var filtereddates = disableddates.filter(function (d) {
return d.getTime() === date.getTime();
});
//return array with TRUE as the first (only) element if there are NO
//matching dates - so a matching date in the array will tell calling
//code to disable that day.
return [filtereddates.length == 0];
}
});
</script>
This appears to work for me.

Remove the time in JQUERY DATETIMEPICKER

How can I disable the past date in datetimepicker2,
For example: I choose July 1, 2015 in datetimepicker1 then the date datetimepicker2 will be disable from July 1, 2015 and the past of the July 1, 2015. Also how to make the time will not appear in the textbox when i choose date.
Here's the screen capture of the Datetimepicker
Here's the structure:
<link rel="stylesheet" type="text/css" href="css/jquery.datetimepicker.min.css">
<script type="text/javascript" src = "js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.datetimepicker.full.js"></script>
I know the src in the top is the directory of the jquery, I just place there if maybe you know this scenario.
//html
<input id ="textin" required>
<input id ="textout" required>
//script
<script>
$('#textin').datetimepicker({
step: 5
});
$('#textin').datetimepicker({
minDate: 0
});
$('#textout').datetimepicker({
step: 5
});
$('#textout').datetimepicker({
minDate: 0
});
</script>
This should do the trick:
var data = {
format: 'd/m/Y', //date format
timepicker: false //hide time
};
const $in = $('#textin'), $out = $('#textout');
$in.datetimepicker(data);
$out.datetimepicker(data);
$in.on('change', function() {
var minDate = $in.val();
if (minDate) {
minDate = minDate.split('/');
console.log(minDate);
minDate = new Date(minDate[2], minDate[1] - 1, minDate[0], 0, 0);
} else {
minDate = new Date(0, 0, 0, 0, 0);
}
data.minDate = minDate;
$out.datetimepicker(data);
});
Try it out on jsfiddle: https://jsfiddle.net/maxbilbow/2ge1gj4j/5/

Categories

Resources