Why date difference start with zero - javascript

Implemented start date and end date to find the day difference. If i select start date today and end date today then difference is showing that 0 and i have disabled the weekends though its counting the weekends also. Here is my code.
$("#startDate").datepicker({
beforeShowDay: $.datepicker.noWeekends,
changeMonth: true,
todayHighlight: true,
minDate: 0,
numberOfMonths: 1,
todayHighlight: true,
onSelect: function(dateStr) {
var min = $(this).datepicker('getDate'); // Get selected date
$("#endDate").datepicker('option', 'minDate', min || '0'); // Set other min, default to today
}
});
$("#endDate").datepicker({
beforeShowDay: $.datepicker.noWeekends,
changeMonth: true,
endDate: true,
todayHighlight: true,
minDate: 0,
numberOfMonths: 1,
buttonImageOnly: true,
onSelect: function(dateStr) {
var max = $(this).datepicker('getDate'); // Get selected date
$('#datepicker').datepicker('option', 'maxDate');
var start = $("#startDate").datepicker("getDate");
var end = $("#endDate").datepicker("getDate");
var days = (end - start) / (1000 * 60 * 60 * 24);
$("#noofDays").val(days);
}
});

Used date difference calculation function in jquery. its working for me
$("#startDate").datepicker({
beforeShowDay: $.datepicker.noWeekends,
minDate: 0,
numberOfMonths: 1,
maxDate: '+1Y+6M',
onSelect: function(dateStr) {
var min = $(this).datepicker('getDate'); // Get selected date
$("#endDate").datepicker('option', 'minDate', min || '0'); // Set other min, default to today
}
});
$("#endDate").datepicker({
beforeShowDay: $.datepicker.noWeekends,
minDate: 0,
numberOfMonths: 1,
onSelect: function(dateStr) {
var max = $(this).datepicker('getDate'); // Get selected date
$('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M'); // Set other max, default to +18 months
var start = $("#startDate").datepicker("getDate");
var end = $("#endDate").datepicker("getDate");
var days = (end - start) / (1000 * 60 * 60 * 24);
$("#noofDays").val(days);
}
});

Related

Jquery Datepicker - Autofill date based on first date without select

Below i have a 2 datepicker which user have to select them and then
the 2nd datepicker will change the min date according to datepicker1
but my goal is to set the 3rd date in datepicker1 and set 7th date in
datepicker 2 without selecting them(Auto).
So far i can able to display the first datepicker with last available
day(3rd date) while i still can't achieve the dates for 2nd
datepicker(7th) :(
Any suggestion?
Here's the code
$(document).ready(function() {
var array = ["15-01-2020","18-01-2020"];
function includeDate(date) {
var dateStr = jQuery.datepicker.formatDate('dd-mm-yy', date);
// Date 0 = Sunday & 6 = Saturday
return date.getDay() !== 0 && array.indexOf(dateStr) === -1;
}
function getTomorrow(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
}
$('#datepicker1').datepicker(
{
defaultDate: "+1d",
inline: true,
showOtherMonths: true,
changeMonth: true,
selectOtherMonths: true,
required: true,
showOn: "focus",
numberOfMonths: 1,
minDate: 1,
beforeShowDay: function(date) {
return [includeDate(date)];
},
maxDate: (function(max) {
var nextAvailable = new Date();
var count = 0;
var extra = 0;
while(count < max) {
nextAvailable = getTomorrow(nextAvailable);
if ( !includeDate(nextAvailable) ) {
extra++;
} else {
count++;
}
}
return max + extra;
})
(3)
});
$('#datepicker1').change(function () {
var from = $('#datepicker1').datepicker('getDate');
// Date diff can be obtained like this without needing to parse a date string.
var date_diff = Math.ceil((from - new Date()) / 86400000);
$('#datepicker2').val('').datepicker({
inline: true,
showOtherMonths: true,
changeMonth: true,
selectOtherMonths: true,
required: true,
showOn: "focus",
numberOfMonths: 1,
minDate: date_diff + 1,
beforeShowDay: function(date) {
return [includeDate(date)];
},
maxDate: (function(max) {
var nextAvailable = $('#datepicker1').datepicker('getDate');
var count = 0;
var extra = 0;
while(count < max) {
nextAvailable = getTomorrow(nextAvailable);
if ( !includeDate(nextAvailable) ) {
extra++;
} else {
count++;
}
}
return max + date_diff + extra;
})
(7)
});
});
$( "#datepicker1" ).datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date()+100);
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<p>datepicker1 <input id="datepicker1"></p>
<p>datepicker2 <input id="datepicker2"></p>
Note
The first datepicker min date is from tomorrow and maxdate is 3 days
which exclude holidays and sundays while the 2nd datepicker mindate is
based on 1st datepicker date and maxdate is 7 days which exclude
holidays and sundays. I just want the last 3rd and 7th date display in
the datepicker input without selecting them.Both input should not
available for choosing(Read-Only).
Updated: At first, I thought there was a bug with the answer code(I didn't really look at it) I provided you from the previous answer. But after looking through the old code again, I realized there isn't a bug with the old code since the datepicker class get remove every time the date picker object get initialize. Thus, I updated this answer to reflect that.
For this code, it is similar to the other code I gave you. It just that when it come to datepicker in a division it is different. However, I commented that into code. For the third datepicker, I compose that datepicker when the first maxDate function run for the first datepicker, then against when the second date picker function maxDate function is run. Since you don't want the user to do anything with the third datepicker, except seeing it, I used a division instead of an input field as a place holder for the third datepicker. They can still select the date but it will not do anything. You probably can add style to those dates to make it seem their selected and unselected states are the same. Also, tool tips can be added.
For this answer, I also give you two versions. The second version is better optimized and more flexible. Version 1 and 2 are the same code. Nonetheless, the second version assign the jQuery object of the 3 datepickers to 3 variables so that every time those divisions is needed to be used, it does not cause jQuery to look up those division objects again. Also, it is easier for you to change their naming context from one place.
Try to play around selecting the first day and you will see the days will dynamically change. Also, if you refer to any of my answer and find any bugs with in them, feel free to notify me of the bugs in the comment. Thank you.
Version 1:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
$(document).ready(function() {
var array = ["15-01-2020","18-01-2020"];
// Store date for datepicker3 here
var dp3 = [];
function includeDate(date) {
var dateStr = jQuery.datepicker.formatDate('dd-mm-yy', date);
// Date 0 = Sunday & 6 = Saturday
return date.getDay() !== 0 && array.indexOf(dateStr) === -1;
}
function getTomorrow(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
}
function dp2ini () {
var from = $('#datepicker1').datepicker('getDate');
// Date diff can be obtained like this without needing to parse a date string.
var date_diff = Math.ceil((from - new Date()) / 86400000);
/*
* For an input field, the hasDatepicker class have to removed
* for the options to take effect if re-initialize. This, can
* also be done with the destroy option of datepicker
* $('#datepicker2').datepicker("destroy"). However, it seem,
* removing its class is faster in this case.
*
* On the other hand if a datepicker widget is a part
* or a division, it has to be destroy as the html
* for the widget is placed as html content inside that division,
* and simply just removing the hasDatepicker class from that division
* will cause the reinitializer to write in a second datepicker widget.
*
* In a division where it only contained the picker
* object, it is faster to just set the HTML to blank
* and remove the hasDatepicker class. On the otherhand,
* for more complicated division, it is better to use,
* the destroy option from "datepicker".
*/
$('#datepicker2').val('').removeClass("hasDatepicker");
$('#datepicker2').datepicker({
inline: true,
showOtherMonths: true,
changeMonth: true,
selectOtherMonths: true,
required: true,
showOn: "focus",
numberOfMonths: 1,
minDate: date_diff + 1,
beforeShowDay: function(date) {
return [includeDate(date)];
},
maxDate: (function(max) {
var nextAvailable = $('#datepicker1').datepicker('getDate');
var count = 0;
var extra = 0;
while(count < max) {
nextAvailable = getTomorrow(nextAvailable);
if ( !includeDate(nextAvailable) ) {
extra++;
} else {
count++;
}
}
dp3[1] = new Date();
dp3[1].setDate( dp3[1].getDate() + max + date_diff + extra );
dp3[1] = dp3[1].toDateString();
// Destroy dp3 and re-initalize it.
//$('#datepicker3').datepicker("destroy");
$('#datepicker3').empty();
$('#datepicker3').removeClass("hasDatepicker");
$( "#datepicker3" ).datepicker({
maxDate: max + date_diff + extra,
beforeShowDay: function(date){
return [date.toDateString() == dp3[0]
|| date.toDateString() == dp3[1]
];
}
});
return max + date_diff + extra;
})(7)
});
}
$('#datepicker1').datepicker({
defaultDate: "+1d",
inline: true,
showOtherMonths: true,
changeMonth: true,
selectOtherMonths: true,
required: true,
showOn: "focus",
numberOfMonths: 1,
minDate: 1,
beforeShowDay: function(date) {
return [includeDate(date)];
},
maxDate: (function(max) {
var nextAvailable = new Date();
var count = 0;
var extra = 0;
while(count < max) {
nextAvailable = getTomorrow(nextAvailable);
if ( !includeDate(nextAvailable) ) {
extra++;
} else {
count++;
}
}
/* Initialize datepicker 3 here. */
// NOTE: If dp1 needed to be reinitialize dp3
// also have to be destroyed and reinitialize.
// The last day will always be a pick-able one...
// Because if it wasn't another day would had been added to it.
dp3[0] = new Date();
dp3[0].setDate( dp3[0].getDate() + max + extra );
dp3[0] = dp3[0].toDateString();
$( "#datepicker3" ).datepicker({
maxDate: max + extra,
beforeShowDay: function(date){
return [date.toDateString() == dp3[0]];
}
});
return max + extra;
})
(3)
});
$( "#datepicker1" ).change(dp2ini);
// Also trigger the change event.
$( "#datepicker1" ).datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date()+100).trigger("change");
});
</script>
<p>datepicker1 <input id="datepicker1"></p>
<p>datepicker2 <input id="datepicker2"></p>
<div id="datepicker3"></div>
Version 2:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
$(document).ready(function() {
var array = ["15-01-2020","18-01-2020"];
// Store date for datepicker3 here
var dp3 = [];
var datepicker1 = $('#datepicker1')
datepicker2 = $('#datepicker2'),
datepicker3 = $('#datepicker3');
function includeDate(date) {
var dateStr = jQuery.datepicker.formatDate('dd-mm-yy', date);
// Date 0 = Sunday & 6 = Saturday
return date.getDay() !== 0 && array.indexOf(dateStr) === -1;
}
function getTomorrow(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
}
function dp2ini () {
var from = datepicker1.datepicker('getDate');
// Date diff can be obtained like this without needing to parse a date string.
var date_diff = Math.ceil((from - new Date()) / 86400000);
/*
* For an input field, the hasDatepicker class have to removed
* for the options to take effect if re-initialize. This, can
* also be done with the destroy option of datepicker
* $('#datepicker2').datepicker("destroy"). However, it seem,
* removing its class is faster in this case.
*
* On the other hand if a datepicker widget is a part
* or a division, it has to be destroy as the html
* for the widget is placed as html content inside that division,
* and simply just removing the hasDatepicker class from that division
* will cause the reinitializer to write in a second datepicker widget.
*
* In a division where it only contained the picker
* object, it is faster to just set the HTML to blank
* and remove the hasDatepicker class. On the otherhand,
* for more complicated division, it is better to use,
* the destroy option from "datepicker".
*/
datepicker2.val('').removeClass("hasDatepicker");
datepicker2.datepicker({
inline: true,
showOtherMonths: true,
changeMonth: true,
selectOtherMonths: true,
required: true,
showOn: "focus",
numberOfMonths: 1,
minDate: date_diff + 1,
beforeShowDay: function(date) {
return [includeDate(date)];
},
maxDate: (function(max) {
var nextAvailable = datepicker1.datepicker('getDate');
var count = 0;
var extra = 0;
while(count < max) {
nextAvailable = getTomorrow(nextAvailable);
if ( !includeDate(nextAvailable) ) {
extra++;
} else {
count++;
}
}
dp3[1] = new Date();
dp3[1].setDate( dp3[1].getDate() + max + date_diff + extra );
dp3[1] = dp3[1].toDateString();
// Destroy dp3 and re-initalize it.
//$('#datepicker3').datepicker("destroy");
datepicker3.empty();
datepicker3.removeClass("hasDatepicker");
datepicker3.datepicker({
maxDate: max + date_diff + extra,
beforeShowDay: function(date){
return [date.toDateString() == dp3[0]
|| date.toDateString() == dp3[1]
];
}
});
return max + date_diff + extra;
})(7)
});
}
datepicker1.datepicker({
defaultDate: "+1d",
inline: true,
showOtherMonths: true,
changeMonth: true,
selectOtherMonths: true,
required: true,
showOn: "focus",
numberOfMonths: 1,
minDate: 1,
beforeShowDay: function(date) {
return [includeDate(date)];
},
maxDate: (function(max) {
var nextAvailable = new Date();
var count = 0;
var extra = 0;
while(count < max) {
nextAvailable = getTomorrow(nextAvailable);
if ( !includeDate(nextAvailable) ) {
extra++;
} else {
count++;
}
}
/* Initialize datepicker 3 here. */
// NOTE: If dp1 needed to be reinitialize dp3
// also have to be destroyed and reinitialize.
// The last day will always be a pick-able one...
// Because if it wasn't another day would had been added to it.
dp3[0] = new Date();
dp3[0].setDate( dp3[0].getDate() + max + extra );
dp3[0] = dp3[0].toDateString();
datepicker3.datepicker({
maxDate: max + extra,
beforeShowDay: function(date){
return [date.toDateString() == dp3[0]];
}
});
return max + extra;
})
(3)
});
datepicker1.change(dp2ini);
// Also trigger the change event.
datepicker1.datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date()+100).trigger("change");
});
</script>
<p>datepicker1 <input id="datepicker1"></p>
<p>datepicker2 <input id="datepicker2"></p>
<div id="datepicker3"></div>

jQuery UI datepicker "defaultDate" selects a weekend date despite "noWeekend" active

I have two jQuery UI date pickers on a form I am building. Most of the functionality is working as expected, except for one thing.
I have weekends disabled on both dates. However, when the defaultDate and minDate lands on a weekend, it doesn't select the next available week day but, rather, it still selects the weekend date.
Any help would be really appreciative :)
var dateFormat = "dd/mm/yy",
from = $("#from")
.datepicker({
dateFormat: dateFormat,
beforeShowDay: $.datepicker.noWeekends,
minDate: "+3d",
defaultDate: "+3d",
changeMonth: true
})
.on("change", function () {
var date2 = from.datepicker('getDate')
date2.setDate(date2.getDate() + 2)
to.datepicker('setDate', date2)
to.datepicker('option', 'minDate', date2)
}),
to = $("#to").datepicker({
dateFormat: dateFormat,
beforeShowDay: $.datepicker.noWeekends,
defaultDate: "+1w",
minDate: "+1w",
changeMonth: true,
numberOfMonths: 1
})
UPDATE
I have solved the issue. Here is the answer for if anyone else is interested. I updated the day number (0-6) the selected date lands on and added so many days to it to avoid the weekend and stored this in a variable min. I then assigned the min variable to the defaultDate and minDate datepicker options :).
var min = 3;
switch (new Date().getDay()) {
case 3:
min = 5;
break;
case 4:
min = 4;
break;
}
var dateFormat = "dd/mm/yy",
from = $("#from")
.datepicker({
dateFormat: dateFormat,
beforeShowDay: $.datepicker.noWeekends,
minDate: min,
defaultDate: min,
changeMonth: true
})
.on("change", function () {
var date2 = from.datepicker('getDate')
min = 2
switch (date2.getDay()){
case 4:
min = 4;
break;
case 5:
min = 4;
break;
}
date2.setDate(date2.getDate() + min)
to.datepicker('setDate', date2)
to.datepicker('option', 'minDate', date2)
}),
to = $("#to").datepicker({
dateFormat: dateFormat,
beforeShowDay: $.datepicker.noWeekends,
defaultDate: "+1w",
minDate: "+1w",
changeMonth: true,
numberOfMonths: 1
})

Setting max date value to current date OR 1 year from start date

What should I do to restrict the user to select the end date beyond one year from the starting date OR the current date. I have my codes like this.
$(function () {
$('#DateFrom').datepicker({
dateFormat:'d-M-y',
changeMonth: true,
changeYear: true,
minDate: new Date(2000, 7, 23),
maxDate: 0,
onSelect: function() {
var date = $('#DateFrom').datepicker('getDate');
date.setTime(date.getTime() + (1000*60*60*24*365));
$('#DateTo').datepicker('option', 'maxDate', date);
$('#DateTo').datepicker('option', 'minDate',$('#DateFrom').datepicker('getDate'));
displayToUser();
},
});
$('#DateTo').datepicker({
dateFormat:'d-M-y',
maxDate: 0,
changeMonth: true,
changeYear: true,
onSelect: displayToUser,
});
});
function displayToUser() {}
Here although it restricts the user within one year from starting date, but it allows the user to select dates beyond the current date.
Example: if start date is 23-01-2016, it allows to select the end date upto 22-01-2017. I want it to be at most today's date.
Does this do it?
$(function () {
$('#DateFrom').datepicker({
dateFormat:'d-M-y',
changeMonth: true,
changeYear: true,
minDate: new Date(2000, 7, 23),
maxDate: 0,
onSelect: function() {
var date = $('#DateFrom').datepicker('getDate');
date.setTime(date.getTime() + (1000*60*60*24*365));
var todaysDate = new Date();
if(date.getTime() > todaysDate.getTime()) date = todaysDate;
$('#DateTo').datepicker('option', 'maxDate', date);
$('#DateTo').datepicker('option', 'minDate',$('#DateFrom').datepicker('getDate'));
displayToUser();
},
});
$('#DateTo').datepicker({
dateFormat:'d-M-y',
maxDate: 0,
changeMonth: true,
changeYear: true,
onSelect: displayToUser,
});
});
function displayToUser() {}
I only added these two lines
var todaysDate = new Date();
if(date.getTime() > todaysDate.getTime()) date = todaysDate;

Datepicker Javascript not fetching tomorrow's date

I want select start date as today's date and end date as tommorrow's date. I am getting start date as today's date (which is correct) but I am getting end date as 12/31/1969. Here's the piece of code:
$("#endOnDate").datepicker({
dateFormat: "mm/dd/yy",
minDate: new Date()
});
$("#startOnDate").datepicker({
dateFormat: "mm/dd/yy",
minDate: new Date(),
onSelect: function(selected) {
$("#endOnDate").datepicker("option", "minDate", selected);
}
});
Plz updateas followes.I have modified it plz find
$("#endOnDate").datepicker({ dateFormat: "mm/dd/yy", minDate: new Date()});
$("#startOnDate").datepicker({ dateFormat: "mm/dd/yy", minDate: new Date(),
onSelect: function (dateText) {
var actualDate = new Date(dateText);
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
alert('fff'+newDate);
$("#endOnDate").datepicker("option", "minDate", newDate);
}});
In the past I managed the start and end date picker to build my own select range valid. So I wish to suggest you:
$( "#startOnDate" ).datepicker({
dateFormat: "mm/dd/yy",
maxDate: new Date(),
onSelect: function(selected) {
$("#endOnDate").datepicker("option", "minDate", selected);
}
}).datepicker('setDate', new Date());
$( "#endOnDate" ).datepicker({
dateFormat: "mm/dd/yy",
minDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
onSelect: function(selected) {
$("#startOnDate").datepicker("option", "maxDate", selected);
}
}).datepicker('setDate', new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
Could you try and let me know? thanks
To initialize the datepicker i added some code. Could you try now and let me know? Thanks

javascript datapicker restrict dates

I have this code to restrict various "datepicker dates". :
$(function() {
$(".datepicker").datepicker({
dateFormat: 'dd-mm-yy'
})({
changeMonth: true,
changeYear: true
});
$(".datepicker").datepicker;
});
var calcDate = function() {
var start = $('#conference_date_in').datepicker('getDate');
var end = $('#conference_date_out').datepicker('getDate');
var days = (end - start) / 1000 / 60 / 60 / 24;
document.getElementById('total_days').value = days;
}
$('#conference_date_out').change(calcDate);
({ minDate: -20, maxDate: "+1M +10D" });
$('#conference_date_in').change(calcDate);
</script>
Is my min/max date in the wrong section?
You have to set mindate and max date like this
$( "#datepicker" ).datepicker({ minDate: -20, maxDate: "+1M +10D" });
Example
Reference: mindate and maxdate
And if you want to disable a specific date range you can use the following code
// unavailable dates range
var dateRange = ["2012/05/20","2012/05/29"]; // yyyy/MM/dd
function unavailable(date) {
var startDate = new Date(dateRange[0]);
var endDate = new Date(dateRange[1]);
var day = date.getDay();
if(date > startDate && date < endDate )
return [false, "disabled"];
else if(day > 0 && day < 6)
return [true, "enabled"];
else
return [false, "disabled"];
}
$('#iDate').datepicker({ beforeShowDay: unavailable });
Working Fiddle

Categories