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.
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.
To filter weekdays or weekend days, you apply Excel's filter to your table (Data tab > Filter) and select either "Workday" or "Weekend".
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');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With