我有兩個日期選擇器,從中我可以計算一天的數量而不用計算週六和週日。但我想在週五和週六做這個。我嘗試了一些不同的方法,但失敗了。這是容易的,我處理天不包括星期六和星期天,但不是爲週五和週六下面的號碼是我的javascript代碼 -使用JavaScript和jQuery UI獲取工作日數日期選擇器
$(function() {
$("#startDate").datepicker({
onSelect: calculateDays});
});
$(function() {
$("#endDate").datepicker({
onSelect: calculateDays});
});
function calculateDays(startDate, endDate) {
var form = this.form
var startDate = document.getElementById("startDate").value;
var startDate = new Date(startDate);
var endDate = document.getElementById("endDate").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 (startDay - endDay > 1)
days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
days = days - 1
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days - 1
if (days)
document.getElementById("result").innerHTML=days;
}
而我的HTML是:
<form id="dateDifference" style="width:200px;">
<input name="startDate" id="startDate" value="" >
<input name="endDate" id="endDate" value="" >
</form>
<span id="result"></span>
此代碼似乎對我有問題...取決於結束日期。 –
@MikeQ示例? – Matt
函數calculateBizDays(sDate,eDate) {varily saturday = 7; var sunday = 1; sDate.setHours(23); //這應該是0,但服務器是按小時關閉的。 sDate.setMinutes(0); sDate.getSeconds(0); eDate.setHours(0); // BPM是HOUR OFF?爲什麼? eDate.setMinutes(59); eDate.getSeconds(59); (((eDate.getTime()* 1000)-sDate.getTime())/(24 * 3600 * 1000)); var nsaturdays = Math.floor((ndays + sDate.getDay())/ 7); return ndays - 2 * nsaturdays - (sDate.getDay()== sunday) - (eDate.getDay()== saturday); } –