Error Converting Epoch to DateTime in SQL Server when epoch is more than a Trillion seconds

耗尽温柔 提交于 2019-12-12 15:04:08

问题


I tried out many answers already given for converting EPOCH to SQL Server datetime. They work when the EPOCH has up to a billion seconds. But as soon as it crosses the Trillion mark it goes bust! E.g. -->

1. SELECT dateadd(MCS,1351187877744,'1970-01-01')
2. SELECT dateadd(NS,1351187877744,'1970-01-01')
3. SELECT dateadd(NANOSECOND, 1351187877744, '1970-01-01 00:00:00.0000000')
4. SELECT convert(bigint, datediff(ss, '01-01-1970 00:00:00',1351187877744))

All the above fail with the following overflow error: "Arithmetic overflow error converting expression to data type int."

Interestingly when I input this date on this site it returns the correct values.

Any suggestions how to do this in a way that works for EPOCHs which are of any magnitude (>trillion secs etc)


回答1:


Try this one -

MSDN :

DATEADD: The number argument cannot exceed the range of int. In the following statements, the argument for number exceeds the range of int by 1. The following error message is returned: "Msg 8115, Level 16, State 2, Line 1. Arithmetic overflow error converting expression to data type int."

Query:

DECLARE 
      @Date DATETIME = '19700101'
    , @MaxInt INT = 2147483647 
    , @ms BIGINT = 1351187877744

WHILE @ms != 0 BEGIN

    SELECT @Date = DATEADD(ms, CASE WHEN @ms > @MaxInt THEN @MaxInt ELSE @ms END, @Date)
    SELECT @ms = CASE WHEN @ms - @MaxInt < 0 THEN 0 ELSE @ms - @MaxInt END

END

SELECT @Date

Output:

2012-10-25 17:57:57.533



回答2:


Simply create this function

CREATE FUNCTION convertEpoch 
(@epochVal bigint) RETURNS datetime 
AS BEGIN DECLARE @Return datetime
SELECT @return = dateadd(s,@epochVal/1000,'1970-01-01')
RETURN @return END



回答3:


As per MSDN the syntax is :

DATEADD (datepart , number , date )

where number Is an expression that can be resolved to an int that is added to a datepart of date. User-defined variables are valid.

Also, Addition for a datepart of microsecond or nanosecond for date data types smalldatetime, date, and datetime is not allowed.

Try this :

DECLARE @datetime2 datetime2 = '2007-01-01 13:10:10.1111111';

SELECT '50 nanoseconds', DATEADD(nanosecond,50,@datetime2)


来源:https://stackoverflow.com/questions/16728211/error-converting-epoch-to-datetime-in-sql-server-when-epoch-is-more-than-a-trill

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!