sql server datetime到bigint(epoch)溢出

its*_*aja 8 sql-server datetime

我有一个'datetime'列,其值为2013-03-22 15:19:02.000

我需要将此值转换为纪元时间并将其存储在"bigint"字段中

上述时间的实际纪元值是,

1363945741898

我用的时候

  select DATEDIFF(s, '1970-01-01 00:00:00', '2013-03-22 15:19:02.000')
Run Code Online (Sandbox Code Playgroud)

我明白了

1363965542

我用的时候

select DATEDIFF(ms, '1970-01-01 00:00:00', '2013-03-22 15:19:02.000')
Run Code Online (Sandbox Code Playgroud)

我明白了

Msg 535,Level 16,State 0,Line 1 dateiff函数导致溢出.分隔两个日期/时间实例的日期部分数量太大.尝试使用具有不太精确的日期部分的datediff.

如何从'datetime'字段中获取确切的纪元值

我使用的是sql server 2008.这也适用于2005.

谢谢.

awe*_*eis 8

这是一个例子,没有经过测试,从免费手写:)

declare @v_Date datetime
set @v_Date = '2013-03-22 15:19:02.000'

declare @v_DiffInSeconds integer
declare @v_DiffInMSeconds bigint

select @v_DiffInSeconds = DATEDIFF(s, '1970-01-01 00:00:00', @v_Date)
select @v_DiffInMSeconds = cast(@v_DiffInSeconds as bigint) * 1000 + cast(DATEPART(ms, @v_Date) as bigint)
Run Code Online (Sandbox Code Playgroud)

编辑 我在下面做了这个例子来说明时区转换.给定的时间戳(以秒为单位,我删除了最后三位"898")在这里通过添加5.5小时(19800秒)转换为本地IST时区,并将其从当地时间转换回时间戳GMT再次.以下计算与问题中的值匹配(以秒为单位).

declare @v_time datetime
set @v_time = '1970-01-01 00:00:00'

declare @v_date datetime
set @v_date = '2013-03-22 15:19:01'

-- This returns "March, 22 2013 15:19:01"
select dateadd(s, (1363945741 + 19800), @v_time)

-- This returns "1363945741"
select datediff(s, @v_time, @v_date) - 19800
Run Code Online (Sandbox Code Playgroud)