I have a code that returns the number of days between two dates selected with jquery datapicker.
I would like to add a function for holidays that will exclude all holidays in an array; var holidays [25-12-2016,26-12-2016,1-1-2017];
please find code below:
<script>
<!--Calculate Leave days excluding weekends
function calcBusinessDays(start, end) {
// This makes no effort to account for holidays
// Counts end day, does not count start day
// make copies we can normalize without changing passed in objects
var start = new Date(start);
var end = new Date(end);
// initial total
var totalBusinessDays = 0;
// normalize both start and end to beginning of the day
start.setHours(0,0,0,0);
end.setHours(0,0,0,0);
var current = new Date(start);
current.setDate(current.getDate() + 1);
var day;
// loop through each day, checking
while (current <= end) {
day = current.getDay();
if (day >= 1 && day <= 5) {
++totalBusinessDays;
}
current.setDate(current.getDate() + 1);
}
return totalBusinessDays;
}
$(function() {
$( "#start_date" ).datepicker({ minDate:0, showOn: 'button', buttonImageOnly: true, buttonImage: 'images/calendar.png', beforeShowDay: $.datepicker.noWeekends });
$( "#end_date" ).datepicker({ minDate:0, showOn: 'button', buttonImageOnly: true, buttonImage: 'images/calendar.png',beforeShowDay: $.datepicker.noWeekends,
onSelect: function (dateStr) {
var max = $(this).datepicker('getDate'); // Get selected date
$('#datepicker').datepicker('option', 'maxDate', max || '+1Y+12M'); // Set other max, default to +18 months
var start = $("#start_date").datepicker("getDate");
var end = $("#end_date").datepicker("getDate");
var days = (end - start) / (1000 * 60 * 60 * 24);
var diff = calcBusinessDays(start,end);
$("#leave_days").val(diff);
} });
});
</script>
<input name="start_date" type="text" id="start_date" />
<input name="end_date" type="text" id="end_date" />
<input name="leave_days" type="text" id="leave_days" size="32" class="form-control"/>
You can use this logic:
Taking weekends as holidays inbetween
Hope this helps!
Like said in comments, you will have to define the holiday array.
For this example, I defined two dates: 2016-11-23 and 2016-12-02
You can use a database or do it manually in script in order to maintain the relevant dates over time.
This part is not explained here, but in the script, I used the default MySQL date format, which is YYYY-MM-DD.
It it should be easy to get holiday dates from a database.
An additionnal function is used to convert
current
date into this MySQL date format, in order to compare it. Then, in thewhile
loop, we check if the date is a holiday and, if so, set a boolean flag used in the condition to add a "business day" or not to the counter.See in CodePen ( Check the console ;) )