# Last Sat of the Previous month

Hello,

How can I calculate the last Saturday of the previous month?

Thanks !
LVL 8
###### Who is Participating?

Commented:
if you want to get remove the time component:
declare @dtX as smalldatetime
--last day of last month
set @dtx = cast(floor(cast((getdate() -(day(getdate()))) as int)) as smalldatetime)
--now last saturday
select
case DATEPART ( dw , @dtx )
when 6 then @dtx
else @dtx - DATEPART( dw , @dtx )
end as 'LastSaturdayOfPreviousMonth'
0

Commented:
declare @YOUR_DATE datetime
set @YOUR_DATE=CONVERT(datetime, '2003/07/01')
select DATEADD(d, (CASE WHEN DATEPART(dw, @YOUR_DATE)>=6 THEN 6-DATEPART(dw, @YOUR_DATE) ELSE -DATEPART(dw, @YOUR_DATE) END), @YOUR_DATE)
0

Commented:
declare @dtX as smalldatetime
set @dtx = getdate() -(day(getdate()))
select case DATEPART ( dw , @dtx )
when 6 then @dtx
else @dtx - DATEPART( dw , @dtx )
end as 'LastSaturday'
0

Author Commented:
Hi,

When I substitute the @YOUR_DATE with getdate( ) it gives the last Sat ie. 11/17/2007.
I would like to know the last Sat of the previous month i.e Oct, it would be 10/27/2007.

Let me explain the context:
I am recursing through a directory and want to know all the log backups in the directory from the last Sat of the previous month (when the last full backup completes) to the first day of the current month.

Thanks a ton!

0

Commented:
sorry, fixed

``````select dateadd(d, -
isnull(nullif(
``````
0

Commented:
this part is repeated:
which essentially is one of 100 ways to get "last day of last month"

if the day of week is not 7 (Sat), we need to make it 7, we do this by simply taking the day of week off! i.e. Wed is 4, so we take 4 days off to make .. Sat.  The trick is that IF it is already Sat, we take none off, hence isnull(nullif(@x, 7), 0) so that 7 becomes 0.

depends on @@datefirst being 1 for Sunday (pretty much all English dbs)
0

Commented:
typo in mine, it should have been 7 instead of a 6.
declare @dtX as smalldatetime
set @dtx = getdate() -(day(getdate()))
select
case DATEPART ( dw , @dtx )
when 7 then @dtx
else @dtx - DATEPART( dw , @dtx )
end as 'LastSaturdayOfPreviousMonth'
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.