Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a date range has a weekend

If I have 2 dates, I know I can work out how many days, hours, minutes etc are between the 2 dates using datediff, e.g:

declare @start datetime;
set @start = '2013-06-14';

declare @end datetime;
set @end = '2013-06-15';

select datediff( hour, @start, @end );

How do I figure out if the date range includes a weekend?

The reason why I want to know if the date range includes a weekend is because I want to subtract the weekend from the day or hour count. i.e. if the start day is Friday, and the end date is Monday, I should only get 1 days or 24 hours.

Datepart 1 = Sunday, and datepart 7 = Saturday on my server.

like image 667
oshirowanen Avatar asked Jun 14 '13 14:06

oshirowanen


People also ask

How do you check if the given date is weekend?

How It Works. The WEEKDAY(Date) function will return a number from 1 to 7 depending on what day of the week the date is. What is this? To find the weekend we need to test if WEEKDAY(Date) equals 1 or 7 which means either a Saturday or a Sunday.

How do I search for weekend dates in Excel?

To filter weekdays or weekend days, you apply Excel's filter to your table (Data tab > Filter) and select either "Workday" or "Weekend".

How do I get weekends in SQL?

Use the DATENAME() function and specify the datepart as weekday . select ID, Name, Salary, Date from dbo. yourTable where datename(weekday, Date) in ('Saturday', 'Sunday');


1 Answers

I have a function that calculates working days between 2 dates, the basic query is

declare @start datetime;
set @start = '2013-06-14';

declare @end datetime;
set @end = '2013-06-17';
SELECT 
   (DATEDIFF(dd, @Start, @end) +1)  -- total number of days (inclusive)
  -(DATEDIFF(wk, @Start, @end) * 2) -- number of complete weekends in period
  -- remove partial weekend days, ie if starts on sunday or ends on saturday
  -(CASE WHEN DATENAME(dw, @Start) = 'Sunday' THEN 1 ELSE 0 END) 
  -(CASE WHEN DATENAME(dw, @end) = 'Saturday' THEN 1 ELSE 0 END) 

so you could work out if dates include weekend if working days different to datediff in days

  SELECT case when  (DATEDIFF(dd, @Start, @end) +1) <>
   (DATEDIFF(dd, @Start, @end) +1)  -- total number of days (inclusive)
  -(DATEDIFF(wk, @Start, @end) * 2) -- number of complete weekends in period
  -- remove partial weekend days, ie if starts on sunday or ends on saturday
  -(CASE WHEN DATENAME(dw, @Start) = 'Sunday' THEN 1 ELSE 0 END) 
  -(CASE WHEN DATENAME(dw, @end) = 'Saturday' THEN 1 ELSE 0 END) then 'Yes' else 'No' end as IncludesWeekends

or simpler

SELECT   (DATEDIFF(wk, @Start, @end) * 2) +(CASE WHEN DATENAME(dw, @Start) = 'Sunday' THEN 1 ELSE 0 END)      +(CASE WHEN DATENAME(dw, @end) = 'Saturday' THEN 1 ELSE 0 END)  as weekendDays
like image 56
JamieA Avatar answered Sep 27 '22 20:09

JamieA