Calculate Business Hours Between Two Dates

Calculate business hours between two dates

Baran's answer fixed and modified for SQL 2005

SQL 2008 and above:

-- =============================================
-- Author: Baran Kaynak (modified by Kodak 2012-04-18)
-- Create date: 14.03.2011
-- Description: 09:30 ile 17:30 arasındaki iş saatlerini hafta sonlarını almayarak toplar.
-- =============================================
CREATE FUNCTION [dbo].[WorkTime]
(
@StartDate DATETIME,
@FinishDate DATETIME
)
RETURNS BIGINT
AS
BEGIN
DECLARE @Temp BIGINT
SET @Temp=0

DECLARE @FirstDay DATE
SET @FirstDay = CONVERT(DATE, @StartDate, 112)

DECLARE @LastDay DATE
SET @LastDay = CONVERT(DATE, @FinishDate, 112)

DECLARE @StartTime TIME
SET @StartTime = CONVERT(TIME, @StartDate)

DECLARE @FinishTime TIME
SET @FinishTime = CONVERT(TIME, @FinishDate)

DECLARE @WorkStart TIME
SET @WorkStart = '09:00'

DECLARE @WorkFinish TIME
SET @WorkFinish = '17:00'

DECLARE @DailyWorkTime BIGINT
SET @DailyWorkTime = DATEDIFF(MINUTE, @WorkStart, @WorkFinish)

IF (@StartTime<@WorkStart)
BEGIN
SET @StartTime = @WorkStart
END
IF (@FinishTime>@WorkFinish)
BEGIN
SET @FinishTime=@WorkFinish
END
IF (@FinishTime<@WorkStart)
BEGIN
SET @FinishTime=@WorkStart
END
IF (@StartTime>@WorkFinish)
BEGIN
SET @StartTime = @WorkFinish
END

DECLARE @CurrentDate DATE
SET @CurrentDate = @FirstDay
DECLARE @LastDate DATE
SET @LastDate = @LastDay

WHILE(@CurrentDate<=@LastDate)
BEGIN
IF (DATEPART(dw, @CurrentDate)!=1 AND DATEPART(dw, @CurrentDate)!=7)
BEGIN
IF (@CurrentDate!=@FirstDay) AND (@CurrentDate!=@LastDay)
BEGIN
SET @Temp = @Temp + @DailyWorkTime
END
--IF it starts at startdate and it finishes not this date find diff between work finish and start as minutes
ELSE IF (@CurrentDate=@FirstDay) AND (@CurrentDate!=@LastDay)
BEGIN
SET @Temp = @Temp + DATEDIFF(MINUTE, @StartTime, @WorkFinish)
END

ELSE IF (@CurrentDate!=@FirstDay) AND (@CurrentDate=@LastDay)
BEGIN
SET @Temp = @Temp + DATEDIFF(MINUTE, @WorkStart, @FinishTime)
END
--IF it starts and finishes in the same date
ELSE IF (@CurrentDate=@FirstDay) AND (@CurrentDate=@LastDay)
BEGIN
SET @Temp = DATEDIFF(MINUTE, @StartTime, @FinishTime)
END
END
SET @CurrentDate = DATEADD(day, 1, @CurrentDate)
END

-- Return the result of the function
IF @Temp<0
BEGIN
SET @Temp=0
END
RETURN @Temp

END

SQL 2005 and below:

-- =============================================
-- Author: Baran Kaynak (modified by Kodak 2012-04-18)
-- Create date: 14.03.2011
-- Description: 09:30 ile 17:30 arasındaki iş saatlerini hafta sonlarını almayarak toplar.
-- =============================================
CREATE FUNCTION [dbo].[WorkTime]
(
@StartDate DATETIME,
@FinishDate DATETIME
)
RETURNS BIGINT
AS
BEGIN
DECLARE @Temp BIGINT
SET @Temp=0

DECLARE @FirstDay DATETIME
SET @FirstDay = DATEADD(dd, 0, DATEDIFF(dd, 0, @StartDate))

DECLARE @LastDay DATETIME
SET @LastDay = DATEADD(dd, 0, DATEDIFF(dd, 0, @FinishDate))

DECLARE @StartTime DATETIME
SET @StartTime = @StartDate - DATEADD(dd, DATEDIFF(dd, 0, @StartDate), 0)

DECLARE @FinishTime DATETIME
SET @FinishTime = @FinishDate - DATEADD(dd, DATEDIFF(dd, 0, @FinishDate), 0)

DECLARE @WorkStart DATETIME
SET @WorkStart = CONVERT(DATETIME, '09:00', 8)

DECLARE @WorkFinish DATETIME
SET @WorkFinish = CONVERT(DATETIME, '17:00', 8)

DECLARE @DailyWorkTime BIGINT
SET @DailyWorkTime = DATEDIFF(MINUTE, @WorkStart, @WorkFinish)

IF (@StartTime<@WorkStart)
BEGIN
SET @StartTime = @WorkStart
END
IF (@FinishTime>@WorkFinish)
BEGIN
SET @FinishTime=@WorkFinish
END
IF (@FinishTime<@WorkStart)
BEGIN
SET @FinishTime=@WorkStart
END
IF (@StartTime>@WorkFinish)
BEGIN
SET @StartTime = @WorkFinish
END

DECLARE @CurrentDate DATETIME
SET @CurrentDate = @FirstDay
DECLARE @LastDate DATETIME
SET @LastDate = @LastDay

WHILE(@CurrentDate<=@LastDate)
BEGIN
IF (DATEPART(dw, @CurrentDate)!=1 AND DATEPART(dw, @CurrentDate)!=7)
BEGIN
IF (@CurrentDate!=@FirstDay) AND (@CurrentDate!=@LastDay)
BEGIN
SET @Temp = @Temp + @DailyWorkTime
END
--IF it starts at startdate and it finishes not this date find diff between work finish and start as minutes
ELSE IF (@CurrentDate=@FirstDay) AND (@CurrentDate!=@LastDay)
BEGIN
SET @Temp = @Temp + DATEDIFF(MINUTE, @StartTime, @WorkFinish)
END

ELSE IF (@CurrentDate!=@FirstDay) AND (@CurrentDate=@LastDay)
BEGIN
SET @Temp = @Temp + DATEDIFF(MINUTE, @WorkStart, @FinishTime)
END
--IF it starts and finishes in the same date
ELSE IF (@CurrentDate=@FirstDay) AND (@CurrentDate=@LastDay)
BEGIN
SET @Temp = DATEDIFF(MINUTE, @StartTime, @FinishTime)
END
END
SET @CurrentDate = DATEADD(day, 1, @CurrentDate)
END

-- Return the result of the function
IF @Temp<0
BEGIN
SET @Temp=0
END
RETURN @Temp

END

How to calculate business hours between two dates when business hours vary depending on the day in R?

Here is something you can try with lubridate. I edited another function I had I thought might be helpful.

First create a sequence of dates between the two dates of interest. Then create intervals based on business hours, checking each date if on the weekend or not.

Then, "clamp" the start and end times to the allowed business hours time intervals using pmin and pmax.

You can use time_length to get the time measurement of the intervals; summing them up will give you total time elapsed.

library(lubridate)
library(dplyr)

calc_bus_hours <- function(start, end) {
my_dates <- seq.Date(as.Date(start), as.Date(end), by = "day")

my_intervals <- if_else(weekdays(my_dates) %in% c("Saturday", "Sunday"),
interval(ymd_hm(paste(my_dates, "09:00"), tz = "UTC"), ymd_hm(paste(my_dates, "21:00"), tz = "UTC")),
interval(ymd_hm(paste(my_dates, "08:00"), tz = "UTC"), ymd_hm(paste(my_dates, "23:00"), tz = "UTC")))

int_start(my_intervals[1]) <- pmax(pmin(start, int_end(my_intervals[1])), int_start(my_intervals[1]))
int_end(my_intervals[length(my_intervals)]) <- pmax(pmin(end, int_end(my_intervals[length(my_intervals)])), int_start(my_intervals[length(my_intervals)]))

sum(time_length(my_intervals, "hour"))
}

calc_bus_hours(as.POSIXct("07/24/2020 22:20", format = "%m/%d/%Y %H:%M", tz = "UTC"), as.POSIXct("07/25/2020 21:20", format = "%m/%d/%Y %H:%M", tz = "UTC"))
[1] 12.66667

Edit: For Spanish language, use c("sábado", "domingo") instead of c("Saturday", "Sunday")

For the data frame example, you can use mapply to call the function using the two selected columns as arguments. Try:

df$business_hours <- mapply(calc_bus_hours, df$start_date, df$end_date)

start end business_hours
1 2020-07-24 22:20:00 2020-07-25 21:20:00 12.66667
2 2020-07-14 21:00:00 2020-07-16 09:30:00 18.50000
3 2020-07-18 08:26:00 2020-07-19 10:00:00 13.00000
4 2020-07-10 08:00:00 2020-07-13 11:00:00 42.00000

How to calculate business hours between two dates in javascript when date difference is large?

I would optimize your problem so that I'd be working with full dates.

If you take your range of 2020-01-01 12:45:00 - 2028-10-06 23:10:33, then there are essentially three parts to this:

  1. 2020-01-01 12:45:00 - 2020-01-01 23:59:59
  2. 2020-01-02 00:00:00 - 2028-10-05 23:59:59
  3. 2020-10-06 00:00:00 - 2028-10-06 23:10:33

Calculating business hours in full days is easy: dayAmount * (dayEnd - dayStart) * 60

Use whatever method you can figure out to calculate minutes in part 1 and 3. Then just sum everything together.

Edit: On the other hand, you might even have to split it into weekly chunks since it might not be a full week. And you'd have to calculate the amount of holidays, unless you're fine with a naive approach.

Calculate working hours between two dates based on business hours

There are multiple phases to this calculation. It may be helpful to look at a calendar for the explanation.

  1. Weeks between start and end
DATEDIFF(WEEK, cte2.START_DATE, cte2.END_DATE) As NumWeeks

This is calculating the difference between the rows of a calendar, a week. (a 7 day period generally represented as a single row on a calendar). Saturday and the following Sunday may only be one day apart, but they are in separate weeks, and therefore are in separate rows on the calendar.




  1. Week Days between start and end.
DATEPART(WEEKDAY, cte2.END_DATE) - DATEPART(WEEKDAY, cte2.START_DATE) as NumDays

Step 1 calculated the difference in rows of the calendar, step 2 we're calculating the difference in columns. This will account for partial week differences.

Tuesday to the following Monday is six days, one day less than a week. Step one returned 1 week. Since we're shifting one column to the left, we adjusting the week by -1 days. If the end date had been Wednesday, it would be 1 week plus 1 day, but since it is Monday, it is 1 week minus 1 day.




  1. Normalizing the Start/End time outside of working hours
CAST(CASE WHEN CAST(CTE.START_DATE AS TIME) < '08:00' THEN '08:00'
WHEN CAST(CTE.START_DATE AS TIME) > '16:00' THEN '16:00'
ELSE CAST(CTE.START_DATE AS TIME)
END AS DATETIME) as StartTimeOnly,
CAST(CASE WHEN CAST(CTE.END_DATE AS TIME) < '08:00' THEN '08:00'
WHEN CAST(CTE.END_DATE AS TIME) > '16:00' THEN '16:00'
ELSE CAST(CTE.END_DATE AS TIME)
END AS DATETIME) as EndTimeOnly

This calculation is only interested in the time, so we cast to Time, then back to DateTime. This sets the Date component for both to 1900-01-01.

Similar to the week & day relationship, an End Time that occurs the next day, but before the Start Time will subtract hours credited from the number of days. For example 1/2 at 12:00 to 1/3 at 10:00 would be 1 day(1/3 - 1/2), or 8 hours, - 2 hours (10-12) = 6 hours of business time.




  1. Calculating the difference in minutes, to ensure partial hours are considered correctly, then converting to hours. This ensures times only a couple minutes apart across an hour boundary don't get counted as a full hour. Of course, the trade off is 59 minutes rounds down to 0 hours.
DATEDIFF(MINUTE, StartTimeOnly, EndTimeOnly)/60 as NumHours

If rounding at the half hour...

CAST(ROUND(DATEDIFF(MINUTE, StartTimeOnly, EndTimeOnly) / 60.0, 0) AS INT) AS RoundedHours



  1. Wrap it all together
,
cte2 AS
(
SELECT CTE.START_DATE,
CTE.END_DATE,
StartTimeOnly = CAST(CASE WHEN CAST(CTE.START_DATE AS TIME) < '08:00' THEN '08:00'
WHEN CAST(CTE.START_DATE AS TIME) > '16:00' THEN '16:00'
ELSE CAST(CTE.START_DATE AS TIME)
END AS DATETIME),
EndTimeOnly = CAST(CASE WHEN CAST(CTE.END_DATE AS TIME) < '08:00' THEN '08:00'
WHEN CAST(CTE.END_DATE AS TIME) > '16:00' THEN '16:00'
ELSE CAST(CTE.END_DATE AS TIME)
END AS DATETIME)
FROM CTE
),
CTE3 AS
(
SELECT START_DATE = CAST(cte2.START_DATE AS DATETIME2(0)),
END_DATE = CAST(cte2.END_DATE AS DATETIME2(0)),
NumWeeks = DATEDIFF(WEEK, cte2.START_DATE, cte2.END_DATE),
NumDays = DATEPART(WEEKDAY, cte2.END_DATE) - DATEPART(WEEKDAY, cte2.START_DATE),
NumHours = DATEDIFF(MINUTE, cte2.StartTimeOnly, cte2.EndTimeOnly)/60
FROM cte2
)
SELECT CTE3.START_DATE,
CTE3.END_DATE,
CTE3.NumWeeks,
CTE3.NumDays,
CTE3.NumHours,
TotalBusinessHours = (CTE3.NumWeeks * 5 * 8) + (CTE3.NumDays * 8) + (CTE3.NumHours )
FROM CTE3
;

For more accurate results, you'll also want to add a table containing your holidays. You'll then subtract the number of holidays found between your start and end date from your total number of days, before converting it to hours.

A question you may still need to answer... what happens if the start and end dates occur during non-working hours? e.g. Start at 19:00 and finish at 20:00. Is that 0 business hours to resolve?

Calculate time difference (only working hours) in minutes between two dates

If you want to do it pure SQL here's one approach

CREATE TABLE working_hours (start DATETIME, end DATETIME);

Now populate the working hours table with countable periods, ~250 rows per year.

If you have an event(@event_start, @event_end) that will start off hours and end off hours then simple query

SELECT SUM(end-start) as duration
FROM working_hours
WHERE start >= @event_start AND end <= @event_end

will suffice.

If on the other hand the event starts and/or ends during working hours the query is more complicated

SELECT SUM(duration) 
FROM
(
SELECT SUM(end-start) as duration
FROM working_hours
WHERE start >= @event_start AND end <= @event_end
UNION ALL
SELECT end-@event_start
FROM working_hours
WHERE @event_start between start AND end
UNION ALL
SELECT @event_end - start
FROM working_hours
WHERE @event_end between start AND end
) AS u

Notes:

  • the above is untested query, depending on your RDBMS you might need date/time functions for aggregating and subtracting datetime (and depending on the functions used the above query can work with any time precision).
  • the query can be rewritten to not use the UNION ALL.
  • the working_hours table can be used for other things in the system and allows maximum flexibility

EDIT:
In MSSQL you can use DATEDIFF(mi, start, end) to get the number of minutes for each subtraction above.

Get total elapsed business hours between two datetimes

finally i write this method ( icluded datetime picker + convert date to Shamsi/Jalali and other helpers method for calculate vacation time

I use MdPersianDateTimePicker for datetime picker
https://github.com/Mds92/MD.BootstrapPersianDateTimePicker

All window.JSAPP.methods.* is my helpers function that i write for this method

 // Get from server ( user config Or settings ) (  this check from server )
var work_group_start_time = window.work_group_start_time; // 09:00:00
var work_group_end_time = window.work_group_end_time; // 18:00:00

var work_group_thursday_start_time = window.work_group_thursday_start_time; // 09:00:00;
var work_group_thursday_end_time = window.work_group_thursday_end_time; // 15:00:00

var min_vacation_time_in_minute = window.min_vacation_time_in_minute; // 60
var max_vacation_time_in_hour = window.max_vacation_time_in_hour; // 18

var hollydays = window.hollydays; // ['2022-01-02']
var v_off_days = window.v_off_days; // ['Friday']

window.JSAPP.methods.disableFormOnSubmit('#vacation-create-form');

var submitButton = document.getElementById('submit_vacation');
var time_input = $("#vacation_time");
submitButton.classList.add("disabled");
submitButton.disabled = true;


var disabledDays = window.JSAPP.methods.disabledDays(v_off_days);


// my datetime picker and its configurations configs ( start date picker )
$('#start_date_text').MdPersianDateTimePicker({
trigger: 'click',
targetTextSelector: '#start_date_text',
targetDateSelector: '#start_date_date',
textFormat:'yyyy/MM/dd HH:mm',
dateFormat:'yyyy_MM_dd___HH__mm',
englishNumber: true,
inLine: false,
disableAfterToday: false,
//disableBeforeToday : true,
enableTimePicker: true,
fromDate: true,
disabledDays : disabledDays,
groupId: 'date_start_end-range',
disabledDates : window.JSAPP.methods.disabledDates(hollydays),
});

// my datetime picker and its configurations configs ( end datetime picker )
$('#end_date_text').MdPersianDateTimePicker({
trigger: 'click',
targetTextSelector: '#end_date_text',
targetDateSelector: '#end_date_date',
textFormat:'yyyy/MM/dd HH:mm',
dateFormat:'yyyy_MM_dd___HH__mm',
englishNumber: true,
inLine: false,
disableAfterToday: false,
enableTimePicker: true,
//disableBeforeToday : true,
toDate: true,
disabledDays : disabledDays,
groupId: 'date_start_end-range',
disabledDates : window.JSAPP.methods.disabledDates(hollydays),
});


// Calculate

var in_day_work_time = (((window.JSAPP.methods.parseTime(work_group_end_time) - window.JSAPP.methods.parseTime(work_group_start_time))/(1000*60))/60);

var in_day_work_thursday_time = (((window.JSAPP.methods.parseTime(work_group_thursday_end_time) - window.JSAPP.methods.parseTime(work_group_thursday_start_time))/(1000*60))/60);

vacationCalculate();

$("#start_date_date , #end_date_date").on('change keyup input focusout',function(){

vacationCalculate();

});


function vacationCalculate(){

time_input.removeClass('text-success');
time_input.removeClass('text-danger');
time_input.val('');
submitButton.classList.add("disabled");
submitButton.disabled = true;

function is_off_day(dayName,date){

if((v_off_days != "undefined" && window.in_array(dayName,v_off_days)) || (hollydays != "undefined" && window.in_array(date,hollydays))){
return true;
}

return false;
}

$("#vacation_time_help").html('');

var vacationTime = 0;

let start_at = $("#start_date_date").val();
let end_at = $("#end_date_date").val();

if((start_at && start_at != null && start_at != '' && start_at.length == 19) && (end_at && end_at != null && end_at != '' && end_at.length == 19)){

start_at = start_at.replace(/___/g,' ').replace(/__/g,':').replace(/_/g,'-');
start_at = start_at+':00';

end_at = end_at.replace(/___/g,' ').replace(/__/g,':').replace(/_/g,'-');
end_at = end_at+':00';

let start_date = start_at.split(' ')[0];
let end_date = end_at.split(' ')[0];

let start_time = start_at.split(' ')[1];
let end_time = end_at.split(' ')[1];

var max_off_time = 0;

// tStart = window.JSAPP.methods.parseTime(start_time,end_date.replace(/-/g,'/'));
// tStop = window.JSAPP.methods.parseTime(end_time,end_date.replace(/-/g,'/'));

var temp_dayName = window.JSAPP.methods.dayName(start_date,'string');

if(temp_dayName === 'Thursday'){
work_group_start_time = work_group_thursday_start_time;
work_group_end_time = work_group_thursday_end_time;
}


if(end_at && start_at){

if(end_at > start_at){

if(start_at !== end_at){

if(start_date === end_date){

let dayName = window.JSAPP.methods.dayName(start_date,'string');

if(!is_off_day(dayName,start_date)){

let _work_group_end_time = work_group_end_time;

if(dayName === 'Thursday'){
_work_group_end_time = work_group_thursday_end_time;
}

if(start_time <= work_group_start_time ){
start_time = work_group_start_time;
}


// if(end_time > _work_group_end_time || end_time < work_group_start_time ){
//
// end_time = _work_group_end_time;
//
// }


if(end_time > _work_group_end_time){

end_time = _work_group_end_time;
}



console.log(start_date+' '+start_time+' --- '+start_date+' '+end_time+' ---- '+((window.JSAPP.methods.parseTime(end_time,start_date) - window.JSAPP.methods.parseTime(start_time,start_date))/(1000*60)));

max_off_time = ((window.JSAPP.methods.parseTime(end_time,start_date) - window.JSAPP.methods.parseTime(start_time,start_date))/(1000*60));
}
}

else{

let start_at_timestamp = window.JSAPP.methods.stringToTimestamp(start_date+" "+"00:00:00");

let end_at_timestamp = window.JSAPP.methods.stringToTimestamp(end_date+" "+"23:59:59");

let vacation_diff = window.JSAPP.methods.diffInDay(start_at_timestamp,end_at_timestamp);


var days = parseInt(vacation_diff.day-1);


for(let i=0; i <= days; i++){


let thisDate;
let diffInM = 0;
let dayName;

thisDate = window.JSAPP.methods.addDays(window.JSAPP.methods.getSafeDate(start_date), i);
dayName = window.JSAPP.methods.dayName(thisDate,'date');


if(i === 0){
if(!is_off_day(dayName,start_date)){


let _work_group_end_time = work_group_end_time;


if(dayName === 'Thursday'){
_work_group_end_time = work_group_thursday_end_time;
}

let _work_group_start_time = work_group_start_time;

// 17:45 <= 18:00:00 && 15:45 >= 9:00:00
if(start_time <= _work_group_end_time && start_time >= work_group_start_time){
_work_group_start_time = start_time;
}

diffInM = ((window.JSAPP.methods.parseTime(_work_group_end_time,start_date) - window.JSAPP.methods.parseTime(_work_group_start_time,start_date))/(1000*60));

console.log(start_date+' '+_work_group_start_time+' --- '+start_date+' '+_work_group_end_time+' ---- '+((window.JSAPP.methods.parseTime(_work_group_end_time,start_date) - window.JSAPP.methods.parseTime(_work_group_start_time,start_date))/(1000*60)));
}

}

else {

if(!is_off_day(dayName,thisDate.yyyymmdd())){

let _work_group_end_time = work_group_end_time;
if(dayName === 'Thursday'){
_work_group_end_time = work_group_thursday_end_time;
}


if(i === days){
if(end_time <= _work_group_end_time && end_time >= work_group_start_time){
_work_group_end_time = end_time;
}
}

let _start_date = thisDate.yyyymmdd();
let _end_date = thisDate.yyyymmdd();


diffInM = ((window.JSAPP.methods.parseTime(_work_group_end_time,_end_date) - window.JSAPP.methods.parseTime(work_group_start_time,_start_date))/(1000*60));


console.log(_start_date+' '+work_group_start_time+' --- '+_end_date+' '+_work_group_end_time+' ---- '+((window.JSAPP.methods.parseTime(_work_group_end_time,_end_date) - window.JSAPP.methods.parseTime(work_group_start_time,_start_date))/(1000*60)));
}
}

if(diffInM > 0){
max_off_time += diffInM;
}
}
}
}

if(max_off_time !== 0){
vacationTime += max_off_time;
}

let calculate_vacation = window.JSAPP.methods.timeParser(vacationTime,9);

if(calculate_vacation.default_min >= min_vacation_time_in_minute){

if(calculate_vacation.day > 0){
$("#vacation_time_help").html('هر روز کاری برابر '+in_day_work_time+' ساعت');
}

if(calculate_vacation.default_min <= max_vacation_time_in_hour*60){
time_input.val(calculate_vacation.string);
time_input.removeClass('text-danger');
time_input.addClass('text-success');
submitButton.classList.remove("disabled");
submitButton.disabled = false;
}
else{
time_input.val('حداکثر مرخصی '+max_vacation_time_in_hour+' ساعت');
time_input.removeClass('text-success');
time_input.addClass('text-danger');
submitButton.classList.add("disabled");
submitButton.disabled = true;
}
}
else{
time_input.val('حداقل مرخصی '+min_vacation_time_in_minute+' دقیقه');
time_input.removeClass('text-success');
time_input.addClass('text-danger');
submitButton.classList.add("disabled");
submitButton.disabled = true;
}
}
else{
time_input.removeClass('text-success');
time_input.addClass('text-danger');


Related Topics



Leave a reply



Submit