I would break down the overall number of ticks into complete Days, Hours, Minutes, Seconds and Milliseconds, then do a DATEADD
for each of those dateparts to build a final datetime value to return.
For example, the UNIX timestamp 14767117605430000
is equivalent to '2016-10-17 13:42:40.543'
if there are 10,000,000 ticks per second, so I would calculate this in T-SQL as follows:
-- ticks per millisecond = 10,000
-- ticks per second = 10,000,000
-- ticks per minute = 600,000,000
-- ticks per hour = 36,000,000,000
-- ticks per day = 864,000,000,000
DECLARE @Datetime BIGINT
SET @Datetime = 14767117605430000
DECLARE @Days INT
DECLARE @Hours INT
DECLARE @Minutes INT
DECLARE @Seconds INT
DECLARE @Milliseconds INT
SET @Days = @Datetime / 864000000000
SET @Hours = (@Datetime - (CONVERT(BIGINT,@Days) * 864000000000)) / 36000000000
SET @Minutes = (@Datetime - (CONVERT(BIGINT,@Days) * 864000000000) - (CONVERT(BIGINT,@Hours) * 36000000000))/ 600000000
SET @Seconds = (@Datetime - (CONVERT(BIGINT,@Days) * 864000000000) - (CONVERT(BIGINT,@Hours) * 36000000000) - (CONVERT(BIGINT,@Minutes) * 600000000)) / 10000000
SET @Milliseconds = (@Datetime - (CONVERT(BIGINT,@Days) * 864000000000) - (CONVERT(BIGINT,@Hours) * 36000000000) - (CONVERT(BIGINT,@Minutes) * 600000000) - (CONVERT(BIGINT,@Seconds) * 10000000)) / 10000
SELECT DATEADD(MILLISECOND, @Milliseconds, DATEADD(SECOND, @Seconds, DATEADD(MINUTE, @Minutes, DATEADD(HOUR, @Hours, DATEADD(DAY, @Days, '1970-01-01')))))
You can obviously change the initial value of @Datetime as desired, maybe wrapping this code into a function or stored procedure as required.
This works for any date value up to '9999-12-31 23:59:59.999'
, so hopefully suits your needs!