码迷,mamicode.com
首页 > 其他好文 > 详细

时间FormatDate自定义函数

时间:2019-03-12 16:43:43      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:string   day   returns   自定义函数   mil   ace   replicat   cas   函数   

Create FUNCTION [dbo].[FormatDate]
(@date as datetime,
@formatstring as varchar(100)
)
RETURNS varchar(100) AS
BEGIN
declare @datestring as varchar(100)

set @datestring=@formatstring

--year
set @datestring=replace(@datestring, ‘yyyy‘, cast(year(@date) as char(4)))
set @datestring=replace(@datestring, ‘yy‘, right(cast(year(@date) as char(4)),2))

--millisecond
set @datestring=replace(@datestring, ‘ms‘, replicate(‘0‘,3-len(cast(datepart(ms,@date) as varchar(3)))) + cast(datepart(ms, @date) as varchar(3)))

--month
set @datestring=replace(@datestring, ‘mm‘, replicate(‘0‘,2-len(cast(month(@date) as varchar(2)))) + cast(month(@date) as varchar(2)))
set @datestring=replace(@datestring, ‘m‘, cast(month(@date) as varchar(2)))

--day
set @datestring=replace(@datestring, ‘dd‘, replicate(‘0‘,2-len(cast(day(@date) as varchar(2)))) + cast(day(@date) as varchar(2)))
set @datestring=replace(@datestring, ‘d‘, cast(day(@date) as varchar(2)))

--hour
set @datestring=replace(@datestring, ‘hh‘, replicate(‘0‘,2-len(cast(datepart(hh,@date) as varchar(2)))) + cast(datepart(hh, @date) as varchar(2)))
set @datestring=replace(@datestring, ‘h‘, cast(datepart(hh, @date) as varchar(2)))

--minute
set @datestring=replace(@datestring, ‘nn‘, replicate(‘0‘,2-len(cast(datepart(n,@date) as varchar(2)))) + cast(datepart(n, @date) as varchar(2)))
set @datestring=replace(@datestring, ‘n‘, cast(datepart(n, @date) as varchar(2)))

--second
set @datestring=replace(@datestring, ‘ss‘, replicate(‘0‘,2-len(cast(datepart(ss,@date) as varchar(2)))) + cast(datepart(ss, @date) as varchar(2)))
set @datestring=replace(@datestring, ‘s‘, cast(datepart(ss, @date) as varchar(2)))

return @datestring
END

时间FormatDate自定义函数

标签:string   day   returns   自定义函数   mil   ace   replicat   cas   函数   

原文地址:https://www.cnblogs.com/skyfeng-826/p/10517679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!