By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
462,955 Members | 776 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 462,955 IT Pros & Developers. It's quick & easy.

how to calculate the number of working hours in Week excluding Weekends in JavaScript

P: 1
please suggest how to code the below scenario with javascript or jquery. I am trying to code a calculator that calculates the time between two dates excluding weekends i.e a task comes to the desk on Friday at 12.00am and ends on coming Tuesday 08:00 am. it should calculate the time between Friday and Tuesday excluding Saturday and Sunday. it should give o/p 56 hrs
Oct 12 '17 #1
Share this Question
Share on Google+
1 Reply

P: 48
This will work:

Expand|Select|Wrap|Line Numbers
  1. var calcWorkHours = function calcWorkHours(start, end) {
  2.         var total = (end - start) / (1000 * 60 * 60 * 24),  // compute difference in days
  3.             totalDays = parseInt(total, 10),                // trim fractional portion
  4.             remainder = (total - totalDays) * 24,           // save fractional portion in hours
  5.             startingDay = start.getDay(),                   // starting weekday
  6.             endingDay = end.getDay(),                       // ending weekday
  7.             possibleWorkingDays = (totalDays * 5),
  8.             actualOccurringWeekends = (startingDay - endingDay) * 2,
  9.             workDays = (possibleWorkingDays - actualOccurringWeekends) / 7;
  10.         if (endingDay === 6) {
  11.             workDays -= 1;  // ends on a weekend, subtract a day
  12.         }
  13.         if (startingDay === 0) {
  14.             workDays -= 1;  // starts on a weekend, subtract a day
  15.         }
  16.         return (workDays * 24) + remainder; // convert to hours and add back fractional portion
  17.     },
  18.     parseInputs = function parseInputs(date, hour, minute) {
  19.         var dmy = date.split("/"),
  20.             now = new Date(),
  21.             thisMinute = now.getMonth() + 1 + "-" + now.getDate() + "-" + now.getFullYear() + " " + now.getHours() + ":" + now.getMinutes() + ":00",
  22.             start = Date.parse(dmy[1] + "-" + dmy[0] + "-" + dmy[2] + " " + hour + ":" + minute + ":00"),
  23.             end = Date.parse(thisMinute);
  24.         start = new Date(start);
  25.         end = new Date(end);
  26.         return calcWorkHours(end, start);
  27.     };
Mar 13 '20 #2

Post your reply

Sign in to post your reply or Sign up for a free account.