如何计算两个选定的日历日期之间的总天数 [英] How to calculate the total days between two selected calendar dates

查看:186
本文介绍了如何计算两个选定的日历日期之间的总天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有startDate = 7/16/2015和endDate = 7/20/2015。这2个日期存储在SharePoint列表中。

Let say i have startDate = 7/16/2015 and endDate = 7/20/2015. This 2 dates are stored in a SharePoint list.

如果用户在SharePoint列表中选择带有日期的确切日期,则可以计算总天数= 2,这意味着

If user select the exact date with the date in SharePoint list, it can calculate the total days = 2 , which means that without calculate on the other days.

有人可以帮忙吗?

我使用以下代码计算差异的总天数,而无需计算周末。但是我不知道如何计算选定日期的总日而不计算其他日期。

I use the following code to calculate the total day of difference without counting on weekend. But I cant figure out the way how to calculate the total day of selected date without counting on other days.

function workingDaysBetweenDates(startDate,endDate) {

// Validate input
if (endDate < startDate)
    return 'Invalid !';

// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1);  // Start just after midnight
endDate.setHours(23,59,59,999);  // End just before midnight
var diff = endDate - startDate;  // Milliseconds between datetime objects    
var days = Math.ceil(diff / millisecondsPerDay);

// Subtract two weekend days for every week in between
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;

return days;

}


推荐答案

以下函数计算两个日期之间的工作日数

The following function calculates the number of business days between two dates

function getBusinessDatesCount(startDate, endDate) {
    var count = 0;
    var curDate = startDate;
    while (curDate <= endDate) {
        var dayOfWeek = curDate.getDay();
        if(!((dayOfWeek == 6) || (dayOfWeek == 0)))
           count++;
        curDate.setDate(curDate.getDate() + 1);
    }
    return count;
}


//Usage

var startDate = new Date('7/16/2015');
var endDate = new Date('7/20/2015');
var numOfDates = getBusinessDatesCount(startDate,endDate);
$('div#result').text(numOfDates);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"/>

这篇关于如何计算两个选定的日历日期之间的总天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆