Search code examples
javascriptdatedatetime

JavaScript: how to pass date values to function


I came across the following function which is used to calculate the difference between two dates in business days, i.e. by eliminating standard weekends / Saturdays and Sunday (source: http://partialclass.blogspot.ie/2011/07/calculating-working-days-between-two.html):

function workingDaysBetweenDates(startDate, endDate) 
{
    if (endDate < startDate)        
        return 0;   

    var millisecondsPerDay = 86400 * 1000; 

    startDate.setHours(0,0,0,1);  
    endDate.setHours(23,59,59,999);  

    var diff = endDate - startDate;  
    var days = Math.ceil(diff / millisecondsPerDay);        
    var weeks = Math.floor(days / 7);    
    var days = days - (weeks * 2);    
    var startDay = startDate.getDay();    
    var endDay = endDate.getDay();        

    if (startDay - endDay > 1)                 
    days = days - 2;              

    if (startDay == 0 && endDay != 6)       
    days = days - 1                  

    if (endDay == 6 && startDay != 0)        
    days = days - 1          

    return days;
    alert(days);
}

Can someone tell me how I can pass two dates to call this function ? My dates would be variables in the format YYYY-MM-DD.

Many thanks for any help with this, Tim


Solution

  • say

    var startDate = "2014-05-22";
    var endDate   = "2014-06-22";
    

    you can call the function like this

    workingDaysBetweenDates(new Date(startDate),new Date(endDate));