MS SQL Date Time to Epoch

August 25, 2008

I know it’s been a while for you programmers out there, but here is an MS SQL function that converts Date Time to Epoch.

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER FUNCTION [dbo].[fn_dateTimeToEpoch] (
 @dateTime DATETIME
)
RETURNS BIGINT
AS
BEGIN

 DECLARE @epochDay BIGINT
 DECLARE @epochSecond INT

 – epoch ‘01-01-1900 00:00:00′
 – one day 86400 seconds

 SET @epochDay = DATEDIFF( day, ‘01-01-1900 00:00:00′, @dateTime )
 – get the remainder
 SET @epochSecond = DATEDIFF( second, ‘01-01-1900 00:00:00′, DATEADD( day, -@epochDay, @dateTime ) )

 – convert to seconds
 RETURN ( @epochDay * 86400 ) + @epochSecond

END

 

Leave a message if you want the Epoch to Date Time function.

Leave a Reply