3

我正在寻找一个高效的 SQL Server 函数(在我的情况下是 2005 年)使用本地时间(特别是考虑到夏令时调整 - 即不仅仅是在几秒钟内添加 01/01/1970)将 unix 时间值转换为 SQL Server 日期时间)

4

2 回答 2

2
SELECT DATEADD(second, @ts, {d '1970-01-01'}) as MSSQLdatetime

获得日期后,您现在可以根据返回日期的 DST 状态在日期上执行 dateadd。要检查 DST,您需要某种形式的函数,示例:

CREATE function [dbo].[fn_GetDaylightSavingsTimeStart]
(@Year varchar(4))
RETURNS smalldatetime
as
begin
 declare @DTSStartWeek smalldatetime, @DTSEndWeek smalldatetime
 set @DTSStartWeek = '03/01/' + convert(varchar,@Year)
 return case datepart(dw,@DTSStartWeek)
 when 1 then
  dateadd(hour,170,@DTSStartWeek)
 when 2 then
  dateadd(hour,314,@DTSStartWeek)
 when 3 then
  dateadd(hour,290,@DTSStartWeek)
 when 4 then
  dateadd(hour,266,@DTSStartWeek)
 when 5 then
  dateadd(hour,242,@DTSStartWeek)
 when 6 then
  dateadd(hour,218,@DTSStartWeek)
 when 7 then
  dateadd(hour,194,@DTSStartWeek)
 end
end

您需要一个模拟函数来查找 DST 何时结束,请查看此站点以获取更多信息: http ://www.mssqltips.com/tip.asp?tip=1372

于 2009-07-24T11:47:40.997 回答
1

更好的?

CREATE FUNCTION [dbo].[UnixTimestampToGMTDatetime] 
(@UnixTimestamp bigint)
RETURNS datetime
AS
BEGIN
       DECLARE @GMTDatetime datetime
       select @GMTDatetime = 
       CASE
       WHEN dateadd(ss, @UnixTimestamp/1000, '1970-01-01') 
       BETWEEN 
           Convert(DATETIME, Convert(VARCHAR(4), Year(dateadd(ss, @UnixTimestamp/1000, '1970-01-01') )) + '-03-' + Convert(VARCHAR(2), (31 - (5 * Year(dateadd(ss, @UnixTimestamp/1000, '1970-01-01') )/4 + 4) % 7)) + ' 01:00:00', 20)
       AND
           Convert(DATETIME, Convert(VARCHAR(4), Year(dateadd(ss, @UnixTimestamp/1000, '1970-01-01') )) + '-10-' + Convert(VARCHAR(2), (31 - (5 * Year(dateadd(ss, @UnixTimestamp/1000, '1970-01-01') )/4 + 1) % 7)) + ' 02:00:00', 20)
       THEN Dateadd(hh, 1, dateadd(ss, @UnixTimestamp/1000, '1970-01-01'))
       ELSE Dateadd(hh, 0, dateadd(ss, @UnixTimestamp/1000, '1970-01-01'))
       END
RETURN @GMTDatetime    
END
于 2013-02-19T16:28:16.080 回答