Convert UTC Milliseconds to DATETIME in SQL server

89,429

Solution 1

DECLARE @UTC BIGINT
SET @UTC = 1348203320997 

SELECT DATEADD(MILLISECOND, @UTC % 1000, DATEADD(SECOND, @UTC / 1000, '19700101'))

Solution 2

Below the function that converts milliseconds to datetime

IF object_id('dbo.toDbTimeMSC', 'FN') IS NOT NULL DROP FUNCTION dbo.toDbTimeMSC
GO
CREATE FUNCTION [dbo].[toDbTimeMSC] (@unixTimeMSC BIGINT) RETURNS DATETIME
BEGIN
    RETURN DATEADD(MILLISECOND, @unixTimeMSC % 1000, DATEADD(SECOND, @unixTimeMSC / 1000, '19700101'))
END
GO

-- select dbo.toDbTimeMSC(1348203320000)

Solution 3

Using SQL Server 2008R2 this produced the required result:

CAST(SWITCHOFFSET(CAST(dateadd(s, convert(bigint, [t_stamp]) / 1000, convert(datetime, '1-1-1970 00:00:00')) AS DATETIMEOFFSET), DATENAME (TZoffset, SYSDATETIMEOFFSET())) AS DATETIME)

Solution 4

The DATEADD requires an integer as a second argument. Your number 1348203320000 is very large for integer therefore it produce an error in runtime. Your should use bigint type instead and provide DATEADD with correct int values by splitting your milliseconds to seconds and milliseconds. That is sample you could use.

DECLARE @total bigint = 1348203320000;

DECLARE @seconds int = @total / 1000
DECLARE @milliseconds int = @total % 1000;

DECLARE @result datetime = '1970-1-1';
SET @result = DATEADD(SECOND, @seconds,@result);
SET @result = DATEADD(MILLISECOND, @milliseconds,@result);
SELECT @result

Solution 5

I had problems with using answers given here (especially that the system was counting ticks form 0001-01-01) - so I did this:

CONVERT(DATETIME,[Time]/ 10000.0/1000/86400-693595)

--explanation for [Time_in_Ticks]/ 10000.0/1000/86400-693595
--Time is in "ticks"
--10000 = number of ticks in Milisecond
--1000  = number of milisecons in second
--86400 = number of seconds in a day (24hours*60minutes*60second)
--693595= number of days between 0001-01-01 and 1900-01-01 (which is base
--          date when converting from int to datetime)
Share:
89,429
Mohan
Author by

Mohan

I am developer. very much keen to work on Microsoft technologies

Updated on January 22, 2022

Comments

  • Mohan
    Mohan over 2 years

    I want to convert UTC milliseconds to DateTime in SQL server.

    This can easily be done in C# by following code:

    DateTime startDate = new DateTime(1970, 1, 1).AddMilliseconds(1348203320000);
    

    I need to do this in SQL server. I found some script here, but this was taking initial ticks from 1900-01-01.

    I have used the DATEADD function as below, but this was giving an arithmetic overflow exception by supping milliseconds as difference:

    SELECT DATEADD(MILLISECOND,1348203320000,'1970-1-1')
    

    How can I do the conversion properly?