Jump to content
Fórum Script Brasil
  • 0

Função para exibição de datas (dica)


Cosme Ferreira

Question

Olá pessoal.

Um amigo que trabalha comigo tem problemas em formatar datas e acabei escrevendo uma funçãozinha para ajudá-lo. Acredito que mais algumas pessoas possam se interessar pela função.

A ideia é passar a data e o formato desejado.

Vamos supor que o retorno desejado seja "12/12/2011".

para isso bastaria passar a data e o formato 'DD/MM/YYYY".

Mas poxa Cosme, eu gostaria de exibir a hora também. Para isso bastaria passar 'DD/MM/YYYY HH:MI'.

A função aceita:

year yy , yyyy

quarter qualquer

month mm

dayofyear dy

day dd

week wk

weekday dw

hour hh

minute mi

second ss

millisecond ms

microsecond mcs

nanosecond ns --MSSQL 2008

TZoffset tz --MSSQL 2008

ISO_WEEK isowk --MSSQL 2008

e os separadores:

'/' - barra

'-' - hifen

':' - dois pontos

' ' - espaço em branco

Não existe a necessidade de passar um separador entre os parâmetros.

Não existe ordem para utilizar os separadores. Os minutos podem vir antes da hora, o mês antes do ano, os segundos junto ao dia.

Exemplo de uso:

select dbo.fncFormatDate(GETDATE(),'dd/mm/yyyy')

Retorno: 12/12/2011

select dbo.fncFormatDate(GETDATE(),'dd/mm/yyyy hh:mi') --

Retorno: 12/12/2011 20:46

select dbo.fncFormatDate(GETDATE(),'DD/MM/YY')

Retorno: 12/12/11

select dbo.fncFormatDate(GETDATE(),'YYYY-SS-DD:MM/qualquer')

Retorno: 2011-18-12:12/4

Caso tenham ficado interessado, segue o código:

CREATE function [dbo].[fncDatePart]

(

@Data datetime,

@Part varchar(5)

)

returns int

as

begin

declare @retorno int

if @part = 'yy'

begin

select @retorno = convert(int,substring(ltrim(rTrim(str(DATEPART(YY,@data)))),3,2))

end

else if @part = 'yyyy'

begin

select @retorno = DATEPART(YYYY,@data)

end

else if @part = 'qualquer'

begin

select @retorno = DATEPART(qualquer,@data)

end

else if @part = 'mm'

begin

select @retorno = DATEPART(MM,@data)

end

else if @part = 'dy'

begin

select @retorno = DATEPART(DY,@data)

end

else if @part = 'dd'

begin

select @retorno = DATEPART(DD,@data)

end

else if @part = 'wk'

begin

select @retorno = DATEPART(WK,@data)

end

else if @part = 'dw'

begin

select @retorno = DATEPART(DW,@data)

end

else if @part = 'hh'

begin

select @retorno = DATEPART(HH,@data)

end

else if @part = 'mi'

begin

select @retorno = DATEPART(MI,@data)

end

else if @part = 'ss'

begin

select @retorno = DATEPART(SS,@data)

end

else if @part = 'ms'

begin

select @retorno = DATEPART(MS,@data)

end

else if @part = 'mcs'

begin

select @retorno = DATEPART(MCS,@data)

end

else if @part = 'ns'

begin

select @retorno = DATEPART(NS,@data)

end

else if @part = 'tz'

begin

select @retorno = DATEPART(TZ,@data)

end

else if @part = 'isowk'

begin

select @retorno = DATEPART(ISOWK,@data)

end

else

select @retorno = ''

return @retorno

end

GO

CREATE function [dbo].[fncFormatDate]

(

@Data datetime,

@Formato varchar(30)

)

returns varchar(256)

as

begin

--remover

--declare @Data datetime,

-- @Formato varchar(30)

--set @Data = GETDATE()

--set @Formato = 'dd/mm/yyyy hh:mi:ss'

/*

year yy , yyyy

quarter qualquer

month mm

dayofyear dy

day dd

week wk

weekday dw

hour hh

minute mi

second ss

millisecond ms

microsecond mcs

nanosecond ns

TZoffset tz

ISO_WEEK isowk

*/

declare @Retorno varchar(256)

set @Retorno = ''

declare @formatos table (cmd varchar(12), part varchar(5))

insert into @formatos (cmd, part)

select 'year' as cmd,

'yy' as part

union all

select 'quarter' as cmd,

'qualquer' as part

union all

select 'month' as cmd,

'mm' as part

union all

select 'dayofyear' as cmd,

'dy' as part

union all

select 'day' as cmd,

'dd' as part

union all

select 'week' as cmd,

'wk' as part

union all

select 'weekday' as cmd,

'dw' as part

union all

select 'hour' as cmd,

'hh' as part

union all

select 'minute' as cmd,

'mi' as part

union all

select 'second' as cmd,

'ss' as part

union all

select 'millisecond' as cmd,

'ms' as part

union all

select 'microsecond' as cmd,

'mcs' as part

union all

select 'nanosecond' as cmd,

'ns' as part

union all

select 'TZoffset' as cmd,

'tz' as part

union all

select 'ISO_WEEK' as cmd,

'isowk' as part

union all

select 'year' as cmd,

'yyyy' as part

union all

select '/' as cmd,

'/' as part

union all

select '-' as cmd,

'-' as part

union all

select ':' as cmd,

':' as part

union all

select ' ' as cmd,

' ' as part

declare @parts table (idx int, part varchar(5), valor varchar(256))

declare @part varchar(5),

@idx int,

@valor varchar(256)

while exists(select 1 from @formatos)

begin

select top 1 @part = part

from @formatos

select @idx = PATINDEX('%'+@part+'%',@Formato)

if @idx > 0

begin

if (@part not in ('/','-',':',' ') )

delete from @parts where idx = @idx

insert into @parts (idx, part)

select @idx, @part

end

delete from @formatos where part = @part

end

declare @char char(01),

@count int

set @count = 1

while (@count < len(@formato))

begin

select @char = SUBSTRING(@Formato,@count,1)

if (@char in ('/','-',':',' '))

begin

delete from @parts where idx = @count

insert into @parts (idx, part, valor)

select @count, @char, @char

select @Formato = substring(@Formato,1,@count -1 ) + '&' + substring(@Formato,@count + 1,LEN(@Formato))

end

set @count = @count + 1

end

--declare @final table (idx int, valor varchar(256))

while exists(select 1 from @parts)

begin

select top 1 @idx = idx,

@part = part,

@valor = valor

from @parts

order by idx

if @valor = ' '

begin

select @Retorno = @Retorno + '#'

end

else if len(isnull(@valor,'')) = 0

begin

--insert into @final (idx, valor)

select @Retorno = @Retorno + ltrim(rtrim(str(dbo.fncDatePart(@Data,@part))))

end

else

begin

select @Retorno = @Retorno + @valor

end

delete from @parts where idx = @idx

end

select @retorno = replace(@Retorno,'#',' ')

return @retorno

end

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152.2k
    • Total Posts
      652k
×
×
  • Create New...