Thanks for this guys, I've been working on the same calculations using a post from Dan Phair to exclude the weekends from the total leave calculation, and have added in the javascript from above to allow the option for a half day selection using a "Yes/No" radio button (defaulting to "No").
Here's the final version, noting that the calculations only work if the date format is dd-MMM-yy (not sure why this is). "sdate" is the CSS class for the leave start date, "edate" is the end date, "total" is the total number of leave days excluding weekends. Hopefully the rest is self-explanatory:
function sumtotal() {
var s = 0;
var e = 0;
//Get dates from input and reformat, then create date var
$('.sdate input').each(function () {
s1 = $(this).val().replace("-", " ");
s2 = s1.replace("-", " 20");
s = new Date(s2);
});
$('.edate input').each(function () {
e1 = $(this).val().replace("-", " ");
e2 = e1.replace("-", " 20");
e = new Date(e2);
});
var one_day = 1000 * 60 * 60 * 24;
var startMillis = s.getTime();
var endMillis = e.getTime();
var totalDays = Math.round((endMillis - startMillis)/one_day);
var weekend = 0;
var days = 0;
for (var i = startMillis; i < endMillis; i += one_day) {
var currentDay = new Date(i);
if (currentDay.getDay() == 5 || currentDay.getDay() == 6) {
weekend++;
}
}
//Check whether the half day radio button is "Yes"
var choice = $('.halfday :checked').val();
if (choice == 'Yes') {
days = (totalDays+1) - 0.5;
} else {
days = (totalDays+1) - weekend;
}
//Output value in the total class box
if (isNaN(days)) {
$('.total input').val('Select dates');
} else {
$('.total input').val(days);
}
if (e.getTime() < s.getTime()) {
$('.edate input').val($('.sdate input').val());
sumtotal();
}
}
$(document).ready(function () {
$(".sdate input").on('blur change', sumtotal);
$(".edate input").on('blur change', sumtotal);
$(".halfday input").on('blur change', sumtotal);
$(".read-only *").prop("readonly", true);
});
It seems to work well, but I'm not a coder so if you have a better approach please feel free to suggest it.