Click here to Skip to main content
12,511,882 members (51,847 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

12.1K views
3 bookmarked
Posted

Get the last working day of the month

, 18 Jul 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Mycroft Holmes
Software Developer (Senior) Contractor
Singapore Singapore
Started my programming life writing Excel 1.0 macros, God what a long time ago.

Now I'm a dotnet developer, I get to influence direction, play with new toys, build stuff, life is wonderful.

Greatest buzz you can get, walk past a row of desks and see your application running on all of them (and getting paid).

Greatest irritant, pouring 12 months of knowledge and experience into an empty head only to have it leave.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralReason for my vote of 5 Why did you need it to be dirty? Qui... Pin
Niklas Lindquist18-Jul-10 23:42
memberNiklas Lindquist18-Jul-10 23:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160929.1 | Last Updated 19 Jul 2010
Article Copyright 2010 by Mycroft Holmes
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid