In this article i will show you how to get first and last date of the previous month from the given date.
Step 1
First we create a user defined function GetFirstDate function,it is look like this
Step 1
First we create a user defined function GetFirstDate function,it is look like this
CREATE FUNCTION dbo.GetFirstDate(@OriginalDate datetime) RETURNS varchar(50) AS BEGIN DECLARE @FirstDate datetime SET @FirstDate=DATEADD(MONTH,-1,DATEADD(DAY,-DATEPART(Day,@OriginalDate)+1, @OriginalDate)) RETURN Convert(varchar(50),@FirstDate,101) END
In this function we get first date of the previous month from given actual date value.
Step 2
Create a user defined function GetLastDate function,it is look like this
CREATE FUNCTION dbo.GetLastDate(@OriginalDate datetime) RETURNS varchar(50) AS BEGIN DECLARE @LastDate datetime SET @LastDate=DATEADD(DAY,-DATEPART(DAY,@OriginalDate), @OriginalDate) RETURN Convert(varchar(50),@LastDate,101) END
Step 3
Call above user defined functions,it is look like this
--Date value must specify on this format --- MM/DD/YYYY SELECT dbo.GetFirstDate('01/18/2010') as 'FirstDate of the Previous Month', dbo.GetLastDate('01/18/2010') as 'LastDate of the Previous Month'
Output
Download
Download SQL Script
No comments:
Post a Comment