28 August 2008

Date Format Backend function

Some days back I was wondering if dateformat is set at the application leval (e.g dd/MM/yyyy or MM/dd/yyyy) then how do I replicate that in the datagrid that I am showing on UI, I tried little bit of manipulation at UI leval but didn't worked out as expected, then I came up with this idea of having a scalar valued function at sql server. This function takes two parameters one is datetime and other is format and returns the formatted date.


CREATE FUNCTION [dbo].[FormatDateTime]
(
@dt DATETIME,
@format VARCHAR(16)
)
RETURNS VARCHAR(64)
AS
BEGIN
DECLARE @dtVC VARCHAR(64)
SELECT @dtVC = CASE @format

WHEN 'MM/DD/YYYY' THEN
CONVERT(CHAR(10), @dt, 101)

WHEN 'DD/MM/YYYY' THEN

CONVERT(CHAR(10), @dt, 103)

WHEN 'dd/MM/yyyy HH:MM' THEN

CONVERT(CHAR(8), @dt, 3) + ' ' +
LTRIM(SUBSTRING(CONVERT(
VARCHAR(20), @dt, 22), 10, 5)
+ RIGHT(CONVERT(VARCHAR(20), @dt, 22), 3))

WHEN 'MM/dd/yyyy HH:MM' THEN

CONVERT(CHAR(10), @dt, 101) + ' ' +
LTRIM(SUBSTRING(CONVERT(
VARCHAR(20), @dt, 22), 10, 5)
+ RIGHT(CONVERT(VARCHAR(20), @dt, 22), 3))

ELSE

'Invalid format specified'

END

if @dtVC ='01/01/1900'
Begin
set @dtVC=''
end

if @dtVc='01/01/00 12:00 AM'
begin
set @dtVc=''
end

if @dtVc='01/01/1900 12:00 AM'
begin
set @dtVc=''
end
RETURN @dtVC
END