Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

Get the last working day of the month

5.00/5 (1 vote)
18 Jul 2010CPOL 28K  
Gets the last week day of the month
I needed a quick and dirty way of getting the last weekday of the month.

ALTER	FUNCTION [fn_LastWorkDay](
	@Date DATETIME)
RETURNS datetime

As
--Note assumes that Sunday = 1 and Saturday = 7
Begin
DECLARE
	@DW INT,
	@EOM DATETIME

	--get the last day of the month
	SET @EOM = DATEADD(hh,-1,DATEADD(mm, DATEDIFF(m,0,@Date  )+1, 0))

	--get the day of the week
	SET @DW = DATEPART(dw,@EOM)

	--make sure it is not a weekend day
	SELECT @EOM = CASE @DW WHEN 1 THEN DATEADD(d,-2,@EOM)
									WHEN 7 THEN DATEADD(d,-1,@EOM)
									ELSE @EOM END 

Return @EOM
End


Usage
SELECT dbo.fn_LastWorkDay(GETDATE())


I am confident there is a better way using nested datepart functions but this works and is simple to understand.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)