Calculating national holidays and weekends in jquery datepicker - javascript

I am stuck in between with my problem of "How to calculate the days between the dates excluding the Weekends(SAT,SUN) and the National Holidays." and really struggling to calculate the weekends and nationaldays holidays both as the same time.
Any Help would be severely appreciated.
I have arrived to the conclusion in my code , that i am getting the calculated days where i am able to exclude the weekends , but not the national holidays, I have tried to built but failed. Please let me know how to calculate both the weekends and national holidays simultaneously.
This is my html code:
<label>Leave From</label>
<input name="from" id="from" type="text" class="form-control" value="" / >
</div>
<div class="form-group" id="to_date">
<label>To</label>
<input name="to" id="to" type="text" class="form-control" >
</div>
<input type="text" id="hasil" name="hasil" readonly />
This is my script:
<script>
var disabledDays = ["3-24-2015", "3-25-2015"];
function nationalDays(date) {
var m = date.getMonth(),
d = date.getDate(),
y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, disabledDays) != -1 || new Date() > date) {
return [false];
}
}
return [true];
}
function noWeekendsOrHolidays(date) {
var noWeekend = jQuery.datepicker.noWeekends(date);
return noWeekend[0] ? nationalDays(date) : noWeekend;
}
$(function () {
$("#from").datepicker({
minDate:0,
changeMonth: true,
constrainInput: true,
numberOfMonths: 1,
beforeShowDay: $.datepicker.noWeekends,
onSelect: calculateDays,
onClose: function (selectedDate) {
var day = $("#from").datepicker('getDate');
$("#to").datepicker("option", "minDate", selectedDate);
},
}).on("changeDate",function(ev){
var fromdate = new Date(ev.date);
fromdate.setMonth(fromdate.getMonth()+1);
var finaldate = fromdate.getFullYear()+"-"+fromdate.getMonth()+"-"+fromdate.getDate();
console.log(finaldate);
$("#fromdate").val(finaldate);
});
});
$(function () {
$("#to").datepicker({
minDate:0,
beforeShowDay: $.datepicker.noWeekends,
changeMonth: true,
constrainInput: true,
numberOfMonths: 1,
onSelect: calculateDays,
onClose: function (selectedDate) {
$("#from").datepicker("option", "maxDate", selectedDate);
},
}).on("changeDate",function(ev){
var todate = new Date(ev.date);
todate.setMonth(todate.getMonth()+1);
var finaldate = todate.getFullYear()+"-"+todate.getMonth()+"-"+todate.getDate();
console.log(finaldate);
$("#todate").val(finaldate);
});
});
function calculateDays(startDate, endDate) {
var form = this.form
var startDate = document.getElementById("from").value;
var startDate = new Date(startDate);
var endDate = document.getElementById("to").value;
var endDate = new Date(endDate);
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var oneDay = 24 * 60 * 60 * 1000;
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / oneDay);
var weeks = Math.floor(days / 7);
var days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (endDate < startDate) {
return 0;
}
if (startDay - endDay > 1) days = days - 2;
if (days) document.getElementById("hasil").innerHTML = days;
$("#hasil").val(days);
}
</script>
Here is the link to jsfiddle: https://jsfiddle.net/8ww4noja/2/

Related

Jquery UI Datepicker - Dependent Datepicker Exclude Holidays in Maxdate

I am trying to exclude Array Dates and Sundays in Dependent Datepicker.
The first datepicker works really well while the second datepicker doesn't exclude Array dates and sundays in Maxdate.
Second datepicker must selectable within 7 working days which should exclude Sunday and Array Dates.
I believe there's should be an easy way to achieve this.
Any Suggestion?
Here's the code :(
$(document).ready(function() {
var d = new Date();
var array = ["10-12-2019","05-12-2019"];
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
today = monthNames[d.getMonth()] + ' ' + d.getDate() + ' ' + d.getFullYear();
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);
}
$('#datepicker2').attr('readonly', 'readonly');
$('#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');
var date_diff = Math.ceil((from.getTime() - Date.parse(today)) / 86400000);
var maxDate_d = date_diff + 7 +'d';
date_diff = date_diff + 'd';
$('#datepicker2').val('').removeAttr('readonly').removeClass('hasDatepicker').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 + extra;
})
(7)
});
});
});
http://jsfiddle.net/nLveychs/83/
For your code, it is almost right. You just forgot one thing for the second date picker. That is, you did not add the date_diff value to the return value of the maxDate() anonymous function. I was going to pass the date_diff by adding it to the parameter. Nonetheless, I found a bug. It can't be done that way, because any previous un-selectable days, will turn into additional extra days. Thus, the only way to add date_diff is start from the day of date picker1 and add the return value of maxDate's anonymous function to date_diff.
I also took out some unnecessary codes. You can just get the date differences simply subtracting datepicker1 date to today date without needing to parse a date string. Plus, date_diff can be as was without needing a "d" to be added to it.
Also, take note that, when you calculate the different days between two dates, for your code, it work that way, because datepicker's date picked object is set to the 0 hour of the day. That code may not work for other scenario. The for sure way to get the day difference between two dates is by setting their hours, minutes, seconds, and milliseconds(if needed) to zeroes.
<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 = ["10-12-2019","05-12-2019"];
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);
}
$('#datepicker2').attr('readonly', 'readonly');
$('#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('').removeAttr('readonly').removeClass('hasDatepicker').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++;
}
}
/*
* Date diffent have to be added to return value.
*/
return max + date_diff + extra;
})
(7)
});
});
});
</script>
<p>datepicker1 <input id="datepicker1"></p>
<p>datepicker2 <input id="datepicker2"></p>

How to get the date difference between two date pickers on clicking the second date picker?

I just want to show the date difference between two jquery date pickers. The differnce should be shown on clicking the second date picker. Following is my code.
<input type ="text" id="Date">
<input type ="text" id="Date2">
$(function () {
var select=function(dateStr) {
var d1 = $('#Date').datepicker('getDate');
var d2 = $('Date2').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
alert(diff);
}
$("#Date").datepicker({
autoclose: true,
todayHighlight: true,
onSelect: select
}).datepicker('update', new Date());
$("#Date2").datepicker({
autoclose: true,
todayHighlight: true,
onSelect: select
}).datepicker('update', new Date());
});
Can anyone help me out?
You can use datepicker's onSelect event , which triggers when a date is being changed on a datapicker.
I also see that you have a typo, , replace var d2 = $('Date2').datepicker('getDate');
with var d2 = $('#Date2').datepicker('getDate');
Something like this:
$("#Date2").datepicker({
onSelect: function(value, date) {
var d1 = $('#Date').datepicker('getDate');
var d2 = $('#Date2').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
alert(diff);
}
});
I think the following code will work
$("#Date2").bind('change keyup', function() {
var date1 = $('#Date').datepicker('getDate');
var date2 = $(this).datepicker('getDate');
var dayDiff = Math.ceil((date2 - date1) / (1000 * 60 * 60 * 24));
alert(dayDiff);
});

Jquery calculate days with datepicker

How is it possible to calculate the total days using interval intitial and final DatePicker. Sorry for my bad english
$(".datepicker").datepicker({
minDate: 0,
numberOfMonths: [3,1],
beforeShowDay: function(date) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
},
onSelect: function(dateText, inst) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
var selectedDate = $.datepicker.parseDate($.datepicker._defaults.dateFormat, dateText);
if (!date1 || date2) {
$("#input1").val(dateText);
$("#input2").val("");
$(this).datepicker();
} else if( selectedDate < date1 ) {
$("#input2").val( $("#input1").val() );
$("#input1").val( dateText );
$(this).datepicker();
} else {
$("#input2").val(dateText);
$(this).datepicker();
}
}
});
http://jsfiddle.net/sWbfk
One way to compute date difference in days is the following:
var t1 = Date.parse($("#input1").val()); // date1.getTime();
var t2 = Date.parse($("#input2").val()); // date2.getTime();
var difference = Math.abs(t2 - t1) / 86400000;
$("#diff").val(difference);
(I tested by putting the code as the last lines of onSelect: function(dateText, inst)).
86400000 is the computed for 24h x 60min x 60s x 1000ms (number of milliseconds in a day)
When you are dealing with dates you should look into moment.js.
You can try something like this:
Moment
moment($("#input1").val()).diff(moment(selectedDate), "days");
Pure JS
var d1 = new Date(date1);
var d2 = new Date(selectedDate);
var secInDays = 24 * 60 * 60 * 1000;
d1.setHours(0, 0, 0, 0);
d2.setHours(0, 0, 0, 0);
console.log((+d2 - +d1) / secInDays)

Calculate date from jquery datepicker

I am calculating the age from jquery datepicker. But this works when only the date is in(mm/dd/yy) format. I need to get this working in dd/mm/yy.
//Code
$('#dob').datepicker({
onSelect: function(value, ui) {
var today = new Date(),
dob = new Date(value),
age = new Date(today - dob).getFullYear() - 1970;
$('#age').text(age);
},
maxDate: '+0d',
yearRange: '1920:2010',
changeMonth: true,
changeYear: true
});
If i try to set dateFormat: 'mm/dd/yy' in the property this wont work.
Any help?
Demo Fiddle mm/dd/yy Demo Fiddle dd/mm/yy
jQuery
onSelect: function (value, ui) {
var today = new Date();
var format = value.split("/");
var dob = new Date(format[2], format[0], format[1]);
var diff = (today - dob);
var age = Math.floor(diff / 31536000000);
$('#age').text(age);
},
Reference
Hope it helps....
Try this:
http://jsfiddle.net/lotusgodkk/GCu2D/120/
Js:
$('#dob').datepicker({
onSelect: function(value, ui) {
console.log(ui.selectedYear)
var today = new Date(),
dob = new Date(value),
age = ui.selectedYear - 1970; //This is the update
$('#age').text(age);
},
maxDate: '+0d',
yearRange: '1920:2010',
changeMonth: true,
changeYear: true,
});
If you inspect the ui object in console, you'll see that it stores year,day,month separately. You can access them like ui.selectedDay or selectedYear . Hope this helps.
this answer will work fine for the all the dates as the month starts from 0 in date function. for date format(dd-mm-yy).
var now= new Date();
var year= now.getFullYear();
$('#dob').datepicker({
onSelect: function (value, ui) {
var today = new Date();
console.log(today.getFullYear());
var format = value.split("-");
console.log(format[2]);
var dob = new Date(format[2], format[1]-1, format[0]);
console.log(dob);
var diff = (today - dob);
var age = Math.floor(diff / 31536000000);
$('#age').text(age);
},
dateFormat: 'dd-mm-yy',
maxDate: '+0d',
yearRange: '1920:'+year,
changeMonth: true,
changeYear: true
});
$("#dob").datepicker({
onSelect: function (value, ui) {
debugger
var today = new Date();
var year = today.getFullYear() - ui.selectedYear;
var month = today.getMonth() - ui.selectedMonth;
var date = today.getDate() - ui.selectedDay;
if ((year == 0 && month == 0 && date < 0) || (year == 0 && month < 0) || (year < 0)) {
$("#lbl6").show();
$("#age").val("");
} else if ((year == 0) || (year > 0 && month == 0 && date >= 0) || (year > 0 && month > 0)) {
$("#age").val(year);
} else if ((year > 0 && month == 0 && date < 0) || (year > 0 && month < 0)) {
$("#age").val(year - 1);
}
},
dateFormat: 'dd M y',
changeMonth: true,
changeYear: true,
yearRange: '1900:2020'
});

How to count days between two dates in javascript

this javascript calculate worng number of the days
i select two dates
1st date 2013-01-01
2nd date 2013-12-31
and it is showing worng answer 365 days
i was calculte manual it is worng correct answer is 364 days
how can i fix this issue please help me
thanks
live demo
form
<input class='fromdate' />
<input class='todate' />
<input class='calculated' />
<input class='minim' /><br/><p><font size="3"><b>For more FAQs Visit<a target="_blank"href="http://jqfaq.com/"</a> JQFaq.com</b></font></p>
<iframe id="iframe1" src="http://jqfaq.com/AdPage.html" style="width:100%; height:115px; border:none;"
/>
javascript
$('.fromdate').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
$('.todate').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
$('.fromdate').datepicker().bind("change", function () {
var minValue = $(this).val();
minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
$('.todate').datepicker("option", "minDate", minValue);
calculate();
});
$('.todate').datepicker().bind("change", function () {
var maxValue = $(this).val();
maxValue = $.datepicker.parseDate("yy-mm-dd", maxValue);
$('.fromdate').datepicker("option", "maxDate", maxValue);
calculate();
});
function calculate() {
var d1 = $('.fromdate').datepicker('getDate');
var d2 = $('.todate').datepicker('getDate');
var diff = 1;
if (d1 && d2) {
diff = diff + Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
$('.calculated').val(diff);
$('.minim').val(d1)
}
Like this way you can do it -
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
Refer this
Try this to calculate the "diff" in function calculate():
if (d1 && d2) {
var timeDiff = Math.abs(d2.getTime() - d1.getTime());
diff = Math.ceil(timeDiff / (1000 * 3600 * 24));
}
In your code the var diff=1 is causing problem.
change it to var diff=1 then see you will get 364 days.

Categories

Resources