sql - 在 SQL 中将纪元转换为 DateTime
问题描述
我有一个提供的 SQL 函数,它将纪元转换为日期时间。
此 sql 函数不适用于 1/3/1970 之前的日期的问题。有没有人有任何想法让这项工作适用于小于 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
推荐阅读
- javascript - 此路由不支持 POST 方法。支持的方法:GET、HEAD。拉拉维尔 8
- sql - 在 Oracle 数据库上的 R 查询,其中日期是从今天开始的 x 天
- mysql - 在左连接中获取中间表列的总和
- object-detection-api - 从保存的检查点恢复训练的 TF2 对象检测 API 问题
- android - 自定义工具栏在 backArrow 和 title 之间添加 imageView
- python - 如何处理来自binance websocket的多个流数据?
- javascript - D3.js 伪3D条形图
- c++ - 如何设置 Astyle 使其不会在同一行格式化两个大括号
- php - 将多选添加到下拉菜单
- loops - 根据 2 列比较 2 个不同的列表