Click here to Skip to main content
15,867,873 members
Articles / Programming Languages / Javascript

Calculating Business Hours in JavaScript

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Jul 2014CPOL1 min read 14K   1
How to calculate business hours in JavaScript

js_business

Time is money, especially when that time is spent handling things like calculating hours worked and filling out time-sheets.

Recently, a user on the forums posed a question about how to go about calculating the number of hours worked between two specified dates. The request required that it must be handled through JavaScript and that it must be as “exact as possible” down to the minute. So I wrote up the following very sub-optimal solution and thought I would post it here on the off-chance that anyone encounters the same issue.

Let’s take a look at what information we need:

  • Define the work hours during the day (i.e. 9AM-5PM)
  • Define a starting and ending date to calculate between
  • Determine if weekends are counted

Using this information, I threw together the following (and I have annotated to help specify what is going on):

JavaScript
// Simple function that accepts two parameters and calculates the number of hours worked 
// within that range
function workingHoursBetweenDates(startDate, endDate) {
    // Store minutes worked
    var minutesWorked = 0;
  
    // Validate input
    if (endDate < startDate) { return 0; }
    
    // Loop from your Start to End dates (by hour)
    var current = startDate;

    // Define work range
    var workHoursStart = 9;
    var workHoursEnd = 18;
    var includeWeekends = false;

    // Loop while currentDate is less than end Date (by minutes)
    while(current <= endDate){          
        // Is the current time within a work day (and if it occurs on a weekend or not)          
        if(current.getHours() >= workHoursStart && current.getHours() <= workHoursEnd 
           && (includeWeekends ? current.getDay() !== 0 && current.getDay() !== 6 : true)){
              minutesWorked++;
        }
         
        // Increment current time
        current.setTime(current.getTime() + 1000 * 60);
    }

    // Return the number of hours
    return minutesWorked / 60;
}

or if you would prefer to pass in all of your variables as parameters, you could use:

JavaScript
// Simple function that accepts two parameters and calculates the number of hours worked 
// within that range
function workingHoursBetweenDates(startDate, endDate, dayStart, dayEnd, includeWeekends) {
    // Store minutes worked
    var minutesWorked = 0;
  
    // Validate input
    if (endDate < startDate) { return 0; }
    
    // Loop from your Start to End dates (by hour)
    var current = startDate;

    // Define work range
    var workHoursStart = dayStart;
    var workHoursEnd = dayEnd;

    // Loop while currentDate is less than end Date (by minutes)
    while(current <= endDate){      
        // Store the current time (with minutes adjusted)
        var currentTime = current.getHours() + (current.getMinutes() / 60);
             
        // Is the current time within a work day (and if it occurs on a weekend or not)          
        if(currentTime >= workHoursStart && currentTime < workHoursEnd && 
            (includeWeekends ? current.getDay() !== 0 && current.getDay() !== 6 : true)){
              minutesWorked++;
        }
         
        // Increment current time
        current.setTime(current.getTime() + 1000 * 60);
    }

    // Return the number of hours
    return (minutesWorked / 60).toFixed(2);
}

or if you want a minified version, thanks to Google’s Online Closure Compiler:

JavaScript
function workingHoursBetweenDates(a,b,e,f,g){var c=0;if(b<a)return 0;
for(;a<=b;){var d=a.getHours()+a.getMinutes()/60;d>=e&&d<f&&(g?0!==a.getDay()&&6!==a.getDay():1)
&&c++;a.setTime(a.getTime()+6E4)}return(c/60).toFixed(2)};

Basically, it simply starts at the beginning time and iterates until the end (while monitoring the number of minutes worked during this period). By no means is this optimal, but it should serve as a very basic example of how to calculate such a value within JavaScript. Please feel free to post any improvements or optimizations within the comments section as this was just a hastily thrown together solution to solve the issue at hand.

You can find a working example here:

You can play around with an interactive example within JS Fiddle

You can play around with an interactive example within JSBin.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
An experienced Software Developer and Graphic Designer with an extensive knowledge of object-oriented programming, software architecture, design methodologies and database design principles. Specializing in Microsoft Technologies and focused on leveraging a strong technical background and a creative skill-set to create meaningful and successful applications.

Well versed in all aspects of the software development life-cycle and passionate about embracing emerging development technologies and standards, building intuitive interfaces and providing clean, maintainable solutions for even the most complex of problems.

Comments and Discussions

 
QuestionWorking hours are from 9 till 17:30 Pin
Mobile.Instinct22-Apr-16 2:12
Mobile.Instinct22-Apr-16 2:12 
Hello,

What value do I set for "dayEnd" if my ending working hour is 17:30? Kindly let me know.

Cheers.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.