SQLServer:将日期时间转为长整型函数F_toUnixTimestamp
JAVA与MYSQL 都有 将 日期时间转为 长整型 函数
SQL SERVER 与C# 都没有自带
以下基于 SQL SERVER 2019 环境做的自定义函数
-- DROP FUNCTION F_toUnixTimestamp64
CREATE FUNCTION F_toUnixTimestamp64(@DATETIME DATETIME2 )
RETURNS BIGINT AS
BEGIN
-- 输出结果将是一个长整型数字,表示从1970年1月1日到指定日期的毫秒数。
declare @result bigint;
declare @initial_datetime datetime ;
set @initial_datetime = CONVERT(DATETIME2,'1970-01-01 00:00:00.0000' ,121);
select @RESULT = DATEDIFF_BIG( millisecond, @initial_datetime, @DATETIME) ;
RETURN(@result);
END;
CREATE FUNCTION F_toUnixTimestamp(@DATETIME DATETIME )
RETURNS BIGINT AS
BEGIN
-- 输出结果将是一个长整型数字,表示从1970年1月1日到指定日期的秒数。
declare @result bigint;
declare @initial_datetime datetime ;
set @initial_datetime = CONVERT(DATETIME2,'1970-01-01 00:00:00.0000' ,121);
select @RESULT = DATEDIFF_BIG( second, @initial_datetime, @DATETIME) ;
RETURN(@result);
END; 测试 :
测试
SELECT DBO.F_toUnixTimestamp(convert( DATETIME2 ,'2025-03-13 20:00:00.0000' ,121) )
结果:
1741896000
以下按北京时间来计算。
CREATE FUNCTION F_LocalDatetime64( @milliSecond bigint)
returns datetime2
as
begin
declare @result datetime2;
declare @second bigint;
declare @milli bigint;
if len(@milliSecond)= 13
begin
-- 以毫秒级的长整型转为 日期时间(北京时间)
set @second = cast( (@milliSecond+28800000)/1000 as BIGint );
select @RESULT = DATEADD(second,@Second,'1970-01-01')
set @milli= substring( cast(@milliSecond as nvarchar(20) ),11,3)
select @result = Dateadd(millisecond, @milli, @result)
end;
else if len(@milliSecond)= 10
select @RESULT = DATEADD(second,@MilliSecond,'1970-01-01')
return(@result);
end;
-- drop FUNCTION F_LocalDatetime ;
CREATE FUNCTION F_LocalDatetime( @Second bigint)
returns datetime2
as
begin
declare @result datetime2;
-- 以秒级的长整型转为 日期时间(北京时间)
select @RESULT = DATEADD(second,@Second+28800 ,'1970-01-01')
return(@result);
end;
select convert( datetime2,17418960003, 121)
--1741854518 : 2025-03-13 16:28:38.0000000
select DATEADD(second,1741854518,'1970-01-01') , DBO.F_LocalDatetime(1741854518) AS DATE_TIME
select dbo.F_LocalDatetime64(1741854518000) as [datetime2]
-- 返回: 2025-03-13 16:28:38.0000000
select cast(1741795200234 as nvarchar(20) )
优质生活从拆开始
浙公网安备 33010602011771号