Excluding weekends from a SQL date range#

Recently I wanted to find the time between 2 datetimes, but I wanted to exclude weekends.  To further complicate matters, I wanted to know hours, not just days.

The "standard" way to do stuff like this is to build out a calendar table that has every date for the next 50 years, along with info like "IsWeekend" or "IsHoliday".

But I found some snippets around that I hoped to use to my advantage, and what I came up with works very well:

DECLARE @start DATETIME
DECLARE @end DATETIME

SET @start = '3/7/08 12:50 pm'
SET @end = '3/11/08 1:50 am'

SELECT (DateDiff(hh, @start, @end) - DateDiff(ww, @start, @end)*2*24)/24.0
       
I won't spend a lot of time explaining why it works, but it basically counts the number of weekend "jumps" that are crossed between the 2 dates, and subtracts accordingly.

 

Categories: Programming | Database | SQL Server
Sunday, March 30, 2008 2:45:05 PM (Central Standard Time, UTC-06:00) #    Comments [3]  | 

 

Wednesday, October 14, 2009 10:42:17 AM (Central Daylight Time, UTC-05:00)
Thank you Very Much.It was becoming so much painful for me but finally i found your article and it worked. Thanks again.
Unknown
Wednesday, October 14, 2009 10:44:38 AM (Central Daylight Time, UTC-05:00)
Thanks for the comment.
Glad it helped!
Friday, February 26, 2010 3:43:54 PM (Central Standard Time, UTC-06:00)
This code doesn't work when the start and end days are Sundays or Saturdays.
unknown
Name
E-mail
(will show your gravatar icon)
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview
All content © 2010, Christopher May, Inc
Open Job Positions
On this page
Google Ads
This site
Calendar
<March 2008>
SunMonTueWedThuFriSat
2425262728291
2345678
9101112131415
16171819202122
23242526272829
303112345
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 2.3.9074.18820

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: