MSSQL
This function will take a format string that has YYYY MM and DD in the string and replace it
with the appropriate date element.
Examples
— Select dbo.FmtDate (‘YYYYMMDD’,getdate())
— Returns 20071214
— Select dbo.FmtDate (‘YYYY-MM-DD’,getdate())
— Returns 2007-12-14
— Select dbo.FmtDate (‘MM/DD/YYYY’,’10/3/2007′)
— Returns 10/03/2007
— Select dbo.FmtDate (‘YYYYMM’,getdate())
— Returns 200712
— Select dbo.FmtDate (‘DD’,getdate())
— Returns 14
— Select dbo.FmtDate (‘Year:YYYY Month:MM Day:DD’,getdate())
— Returns ‘Year:2007 Month:12 Day:14’
Author: Todd Harnar
— Author: Todd Harnar
— Email: tharnar@hotmail.com
— Code may be used as long as Author and Email address
— remains as part of comments.
— Create date: 12/14/2007
— Description: Return date based on format string
— This function will take a format string that has
— YYYY MM and DD in the string and replace it
— with the appropriate date element
—
—
— Examples
— Select dbo.FmtDate (‘YYYYMMDD’,getdate())
— Returns 20071214
— Select dbo.FmtDate (‘YYYY-MM-DD’,getdate())
— Returns 2007-12-14
— Select dbo.FmtDate (‘MM/DD/YYYY’,’10/3/2007′)
— Returns 10/03/2007
— Select dbo.FmtDate (‘YYYYMM’,getdate())
— Returns 200712
— Select dbo.FmtDate (‘DD’,getdate())
— Returns 14
— Select dbo.FmtDate (‘Year:YYYY Month:MM Day:DD’,getdate())
— Year:2007 Month:12 Day:14′
— =============================================
CREATE FUNCTION [dbo].[FmtDate]
(— String should contain at least one of the following date elements
— YYYY, MM or DD
@FmtStr varchar(50),— Date to be formatted
@Dt datetime)
RETURNS varchar(50)
AS
BEGIN— String to hold formatted date
Declare @tmpstr as varchar(50)— Element values of supplied date
Declare @tmpMonth as varchar(2)
Declare @tmpDay as varchar(2)
Declare @tmpYear as varchar(4)Set @tmpStr = @fmtStr
— Determine Date Elements
Set @tmpDay = RIGHT((‘0’ + convert(varchar(2),DAY(@dt))),2)
Set @tmpMonth = RIGHT((‘0’+ convert(varchar(2),MONTH(@dt))),2)
Set @tmpYear = convert(varchar(4),YEAR(@dt))— Replace Date Elements in supplied format string
SELECT @tmpstr = REPLACE(@tmpstr,’YYYY’,@tmpYear)
SELECT @tmpStr = REPLACE(@tmpstr,’MM’,@tmpMonth)
SELECT @tmpStr = REPLACE(@tmpstr,’DD’,@tmpDay)–Return result
RETURN @tmpstrEND
Disclaimer: We hope that the information on these script pages is
valuable to you. Your use of the information contained in these pages,
however, is at your sole risk. All information on these pages is provided
“as -is”, without any warranty, whether express or implied, of its accuracy,
completeness, or fitness for a particular purpose…
Disclaimer Continued
Back to Database Journal Home