SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Calculating the Number of Business Hours Passed Since a Point of Time

By Mazharuddin Ehsan,

Calculating the number of hours passed since a point of time

This set of user defined functions is used to calculate the number of hours passed since a given date and time excluding the non-working hours . The set contains 8 functions. The function which is called to do the job is [CalcTimeSinceCreated]. This function takes a datetime type value as input. All the other 7 functions are used internally.

This code assumes the working schedule as follows:

  • 8 working hours per day from 7.30 AM to 4.00 PM
  • Lunch period from 11.30 AM to 12 Noon.
  • Saturday & Sunday as off days

The code can be modified to suit any other working hours and days pattern. I used this code to calculate the actual number of working hours passed since a job was started. It can be modified to calculate the number of working hours taken to complete tasks (The function CalcTimeSinceCreated will have to be modified to take two parameters in that case as 'task beginning date&time' and 'task ending date&time', instead of one at present).

Suppose the time right now is November 20, 2 PM and we want to calculate the number of working hours passed since November 16, 3:30 PM. The function will give the result 14.5 hours.

select dbo.CalcTimeSinceCreated('2007-11-16 15:30')

Result = 14.5

The calculation goes as follows:

Date Day Hours Explanation
November 16 Friday 0.5 hours The task started at 3.30 PM and the working hour is upto 4.00 PM
November 17 Saturday 0 hours Saturday is an off day
November 18 Sunday 0 hours Sunday is a off day
November 19 Monday 8 hours 8 full hours in the day
November 20 Tuesday 6 hours From 7.30 AM to 2 PM excuding half an hour for the lunch time
Total Hours: 14.5

Total article views: 2953 | Views in the last 30 days: 8
Related Articles

Format Phone Number function

Function to format phone numbers entered as text.


How do I calculate the week number given a date?

How do I calculate the week number given a date?


lag function calculation

llag function calculation


SQL BLOG: Calculating total number of days from 1st Jan without using DATEDIFF function

Below script will calculate total number of days based on the input from user from 1st Jan. Though w...


Calculating Stock Returns Using the ROW_NUMBER function and CTEs

In finance, when pricing data isn't available on last day of week, month or year, calculating return...