我提供了一个 SQL 函数,可以将纪元转换为日期时间。
这个sql函数的问题不起作用适用于 1970 年 1 月 3 日之前的日期。有没有人有任何想法可以使其适用于 1970 年以内的日期。
DECLARE @total bigint
--if greater than 12/31/9999 return null
IF @total > 253402232400000
RETURN NULL
--if less than or equal 1/3/1970 return null
IF @total <= 18000000
RETURN NULL
DECLARE @seconds int = @total / 86400000;
DECLARE @milliseconds int = @total % 86400000;
DECLARE @result datetime = '1970-1-1';
SET @result = DATEADD(DAY, @seconds,@result);
SET @result = DATEADD(MILLISECOND, @milliseconds,@result);
RETURN @result;
尝试这个。
应该适用于所有日期0001-01-01T00:00:00.000
通过9999-12-31T23:59:59.999
.
-- UnixTimeToDateTime2
--
-- Parameter: 64-bit integer
-- Number of milliseconds
-- since 1970-01-01T00:00:00.000
-- May be negative before 1970
--
-- Returns datetime2
-- Works with all values in
-- range 0001-01-01T00:00:00.000
-- through 9999-12-31T23:59:59.999
-- Returns NULL if parameter is out of range
create function dbo.UnixTimeToDateTime2(@x bigint)
returns datetime2
as
begin
return
case
-- If the parameter is out of range,
-- return NULL
when ( @x < -62135596800000 )
or ( @x > 253402300799999 ) then null
else
-- We would like to add this number of milliseconds
-- directly to 1970-01-01T00:00:00.000, but this
-- can lead to an overflow.
-- Instead we break the addition into a number of days
-- and a number of milliseconds.
-- To get the number of days, we divide by the number
-- of milliseconds in a day. Then add the remainder.
dateadd ( millisecond,
@x % 86400000,
dateadd ( day,
@x / 86400000,
cast( '1970-01-01T00:00:00.000'
as datetime2 )) )
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)