How to convert Epoch to DateTime SQL Server if epoch exceeds the year 2038?
Answer in Convert Epoch to DateTime SQL Server will not work.
Example:
SELECT DATEADD(ss, 2713795200000 / 1000, '19700101')
Thu, 30 Dec 2055 16:00:00 GMT
How to convert Epoch to DateTime SQL Server if epoch exceeds the year 2038?
Answer in Convert Epoch to DateTime SQL Server will not work.
Example:
SELECT DATEADD(ss, 2713795200000 / 1000, '19700101')
Thu, 30 Dec 2055 16:00:00 GMT
5条答案
按热度按时间wfypjpf41#
DATEADD function assumes an INT as an increment to your date, to bypass the limitation of INT you can either reduce the precision of your epoch, or do a slightly complex code to retain the precision of your epoch.
This reduces the precision to minutes:
This one splits your epoch to days and milliseconds and then combines them in a datetime
However, I'm not quite sure why the 2nd solution is not as precise as I expect it to be.
uelo1irk2#
Building on the response above, the solution provided works but does not protect from trying to convert to a date that is out of bounds for SQL server.
create function dbo.unixTimestampConversion ( @unixTime bigInt ) returns dateTime2(7) as begin
;
w46czmvw3#
You can assign the epoch time to your datetime directly (I tried this on SQL Server 15.0). Although it considers the number as the number of days since 1900-1-1 00:00:00 so you have to add 2208988800 (the number of seconds in 70 years) and then divide by 86400(number of seconds in a day).
However, it seems to be 0.007s or 0.003s behind the given epoch. Also, I'm not sure if this is faster than the
DATEADD()
function.ccrfmcuu4#
Old question, but later versions of SQL Server that support the
DATETIMEOFFSET
data type have made this easier:DATEADD
can work withs
/second
,ms
/millisecond
,mcs
/microsecond
, andns
/nanosecond
.Then, if you need it in a specific time zone, use
SELECT <date> AS TIME ZONE <timezone>
.ggazkfy85#
create a function to convert epoch to datetime and use them in your query like below
and then use this function in your query