使用SQL Server查询纪元时间以查找日期范围

时间:2016-01-11 20:11:50

标签: sql-server epoch

我必须查询SQL Server数据库,并且表的值使用Epoch时间(int。这里是一个例子 - 1438005018)。我想知道如何编写查询以便我可以说以下内容......

select
  * 
from 
  tablename
where
  epochdate between 'yesterday at 12:00' and 'today at 12:00' --this is the part I'm not sure about.

理想情况下,如果它很简单,我希望查询使用非纪元逻辑,因为Epoch时间会混淆我的废话。也许在SQL Server中有一种快速的转换方式?

2 个答案:

答案 0 :(得分:2)

我在评论中发布了上述链接,如果您能够在您正在使用的数据库中部署功能,那么这可能是一个更实用的解决方案,但如果您只能查询,这是一个尝试的选项(这假设SQL Server 2008及更高版本):

declare @todayepoch bigint, @yesterdayepoch bigint;

select @todayepoch = 
          cast((cast(dateadd(hour, 12, 
             cast(cast(sysutcdatetime() as date) as datetime)) as decimal(24,10))
                - cast(cast('1970-01-01' as datetime) as decimal(24,10)))
                    *60.0*60.0*24.0 as int), -- + 18000, --Eastern time
      @yesterdayepoch = 
          cast((cast(dateadd(hour, -12, 
             cast(cast(sysutcdatetime() as date) as datetime)) as decimal(24,10))
                - cast(cast('1970-01-01' as datetime) as decimal(24,10)))
                    *60.0*60.0*24.0 as int) -- + 18000 --Eastern time

select @todayepoch, @yesterdayepoch

    select
      * 
    from 
      tablename
    where
      epochdate between @yesterdayepoch and @todayepoch

我使用上面的UTC作为基于UTC时间进行比较的假设,但您也可以与您的时区进行比较,并以秒为单位对您的时区差异进行适当的加/减(例如,为每个变量添加18000以获得东部标准时间中午。)

您可以使用http://www.epochconverter.com/比较变量中的值来测试结果。

答案 1 :(得分:1)

您的查询将如下所示:

DECLARE @dt_from DATETIME;
DECLARE @dt_to DATETIME; 
SELECT 
    @dt_from=DATEADD(HH,-12,CAST(FLOOR(CAST(GETUTCDATE() AS FLOAT)) AS DATETIME)), -- strip time of current UTC date/time, and subtract 12 hrs
    @dt_to=DATEADD(HH,+12,CAST(FLOOR(CAST(GETUTCDATE() AS FLOAT)) AS DATETIME));   -- strip time of current UTC date/time, and add 12 hrs

SELECT
    *
FROM
    tablename
WHERE
    epochdate BETWEEN DATEDIFF(s,'1970-01-01',@dt_from) AND DATEDIFF(s,'1970-01-01',@dt_to);