MSSQL:自定义时间转时间戳函数 F_TOUnixTimestamp()

SQL SERVER 2008 版本

做两日期减运算,

使用DATEDIFF( second, '1970-01-01', getdate() )  返回值: 最大2的31次的整数,

当日期getdate()>= 2037-01-19 时函数溢出报错,在指定平台环境下如何 解决日期getdate()>= 2037-01-19 返回时间戳?

在SQL SERVER 2016以及更高版本里有DATEDIFF_BIG() 函数, 此函数可以解决。但在 SQL SERVER 2008 版本里 没有 DATEDIFF_BIG() 函数,

解决 超过68年的BUG,在自定义函数里通过WHILE循环多次使用 DATEDIFF() 处理,具体函数代码:

IF OBJECT_ID('F_toUnixTimestamp')>0 
drop FUNCTION F_toUnixTimestamp;
GO 
CREATE FUNCTION F_toUnixTimestamp(@DATETIME DATETIME ) 
RETURNS BIGINT AS 

BEGIN
-- 参数: @datetime :是北京时间的日期时间格式
-- 输出结果将是一个长整型数字,表示从1970年1月1日到指定日期的秒数(UTC时间)。
-- 返回: UTC 时间戳(10位整数型)
  declare @result bigint, @result1 bigint,  @result2  bigint;
  declare @initial_datetime datetime2  ;
  declare @datetime2 datetime2 , @startdatetime datetime2 ;
  declare @mod bigint , @year bigint, @initial_year bigint ;
  declare @i bigint , @times bigint, @max bigint; 
 -- declare @datetime datetime;
 -- set @datetime = CONVERT(DATETIME2,'2108-01-01 00:00:00.0000' ,121);
 -- set @datetime2 = CONVERT(DATETIME2,'2038-01-01 00:00:00.0000' ,121);
  set @initial_datetime = CONVERT(DATETIME2,'1970-01-01 00:00:00.0000' ,121);
 -- select @RESULT = DATEDIFF( second, @initial_datetime , @DATETIME) - 28800 ; 
  
  set @year = DATEPART(year, @datetime ) ;
  set @i = 1 ;
  set @result2 = 0;
  set @result1 = 0;
  set @result = 0; 
  select  @times = (@year - 1970 )/ 68 , @max = ceiling((@year - 1970 )/ 68.0 );
 -- print ' @times =' + str(@times ) + ' @max = '+str(@max) 
  while @i<@max  
  begin
  -- 4354790400 
         if @i<=@times
         begin
		   set @datetime2 =  DATEADD(year,68* (@i+1) , @initial_datetime  )  ;
		   set @result1 = DATEDIFF( second,  DATEADD(year,68* (@i) , @initial_datetime  ) , @DATETIME2) ;
		 --  print '@result1_i= ' +str(@result1);
		   set @result2 = @result2 + @result1 ;
		 end;
		 if @i=@times and @i<@max 
         begin
		   set @datetime2 =  @datetime ; --DATEADD(year,68* (@i) , @initial_datetime  )  ;
		   set @result1 = DATEDIFF( second,  DATEADD(year,68* (@i) , @initial_datetime  ) , @DATETIME2) ;
		 --  print '@result1_2= ' +str(@result1);
		   set @result2 = @result2 + @result1 ;
		 --  print '@result2_2= ' +str(@result2);
		 end;		 

     set @i = @i+1;
	-- SET @result2 = @result2 + @result1 ;
	 
	 -- print ' @times =' + str(@times ) + ' ; @max = '+str(@max)  + ' ;@i = ' + cast(@i as nvarchar(10))
  end; 
  if  @times = 0 
		   select @RESULT = DATEDIFF( second, @initial_datetime , @DATETIME) - 28800 ; 
  else
    set @result = @result2  - 28800 ; 
  
  return @result ;
 --  print '@result= ' + cast ( @result as nvarchar(200));
END; 

SELECT [dbo].[F_toUnixTimestamp64]( '2258-01-01 00:20:00')  AS toUnixTimestamp64 ,
 [dbo].[F_toUnixTimestamp]( '2258-01-01 00:20:00')  AS toUnixTimestamp

  

 

posted @ 2025-11-07 07:36  samrv  阅读(12)  评论(0)    收藏  举报