ms sql server中实现的unix时间戳函数(含生成和格式化,可以和mysql兼容)

时间:2022-08-28 22:41:01

直接上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
CREATE FUNCTION UNIX_TIMESTAMP (@ctimestamp datetime) RETURNS integer
AS
BEGIN
 /* Function body */
 declare @return integer
 SELECT @return = DATEDIFF(SECOND,{d '1970-01-01'}, @ctimestamp)
 return @return
END
 
 
CREATE FUNCTION from_unixtime (@ts integer) RETURNS datetime
AS
BEGIN
 /* Function body */
 declare @return datetime
 select @return = DATEADD(second, @ts, {d '1970-01-01'})
 return @return
END

用法

跟MySQL下的一样类似:

?
1
2
select dbo.UNIX_TIMESTAMP('2013-1-1')
select dbo.from_unixtime(2145000000)