2012-09-21 11 views
17

Voglio convertire i millisecondi UTC in DateTime nel server SQL.Converti millisecondi UTC in DATETIME nel server SQL

Questo può essere fatto facilmente in C# per codice seguente:

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

Ho bisogno di fare questo in SQL Server. Ho trovato alcuni script here, ma questo stava prendendo le zecche iniziali dal 1900-01-01.

Ho usato la funzione DATEADD come sotto, ma questa è stata un'eccezione dando overflow aritmetico da supping millisecondi come differenza:

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

Come posso fare la conversione correttamente?

risposta

33
DECLARE @UTC BIGINT 
SET @UTC = 1348203320997 

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

Il numero DATEADD richiede un numero intero come secondo argomento. Il numero 1348203320000 è molto grande per numero intero e pertanto genera un errore in runtime. Dovresti invece usare il tipo bigint e fornire a DATEADD i valori int corretti dividendo i millisecondi in secondi e millisecondi. Questo è un esempio che potresti usare.

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 
1

Ho avuto problemi con l'utilizzo di risposte qui riportati (in particolare che il sistema stava contando forma zecche 0001-01-01) - così ho fatto questo:

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) 
2

Sotto la funzione che converte millisecondi 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 

- selezionare dbo.toDbTimeMSC (1348203320000)

-1

Utilizzo di SQL Server 2008R2 ha prodotto il risultato richiesto:

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) 
Problemi correlati