2010-01-22 19 views

risposta

19
SELECT DATEDIFF (MyUnits, '2010-01-22 15:29:55.090', '2010-01-22 15:30:09.153') 

sostitutivi "MyUnits" sulla base di DATEDIFF on MSDN

0

check DateDiff su libri online.

8
SELECT DATEDIFF(day, '2010-01-22 15:29:55.090', '2010-01-22 15:30:09.153') 

Sostituire day con altre unità che si desidera ottenere la differenza, come second, minute ecc

73

Solo un avvertimento per aggiungere circa DateDiff, conta il numero di volte che si passa il confine si specifica come le tue unità, quindi è soggetto a problemi se stai cercando un intervallo preciso. ad es.

select datediff (m, '20100131', '20100201') 

dà una risposta di 1, perché ha attraversato il confine da gennaio a febbraio, quindi, anche se la durata è di 2 giorni, datediff sarebbe restituire un valore di 1 - 1 attraversava la data limite.

select datediff(mi, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153') 

dà un valore di 1, ancora una volta, passò il confine minuto una volta, quindi, anche se è di circa 14 secondi, sarebbe essere restituito come un solo minuto quando si utilizza verbale, per le unità.

+8

+1 per essere l'unico a menzionare questo comportamento. Ha causato un problema inaspettato per me una volta perché non ho RTFM :) – Thorarin

4

Internamente in SQL Server le date sono memorizzate come 2 numeri interi. Il primo numero intero è il numero di date precedenti o successive alla data di base (1900/01/01). Il secondo intero memorizza il numero di tick dell'orologio dopo la mezzanotte, ogni tick è 1/300 di secondo.

More info here

A causa di questo, spesso trovo il modo più semplice per confrontare le date è a loro sottrarre semplicemente. Questo gestisce il 90% dei miei casi d'uso. Per esempio,

select date1, date2, date2 - date1 as DifferenceInDays 
from MyTable 
... 

Quando ho bisogno di una risposta in unità diverse dai giorni, userò DateDiff.

+4

Nota che questo si applica solo al vecchio tipo 'DATETIME', non a' DATE', 'TIME' o' DATETIME2'. Inoltre, il valore restituito sarà un altro 'DATETIME', quindi dovrai lanciarlo per ottenere il numero di giorni leggibile da un utente all'altro. –

0

Quindi questa non è la mia risposta, ma ho appena trovato questo mentre cercando in giro online per una domanda come questo pure. Questo ragazzo ha impostato una procedura per calcolare ore, minuti e secondi. Il link ed il codice:

--Creating Function 
If OBJECT_ID('UFN_HourMinuteSecond') Is Not Null 
Drop Function dbo.UFN_HourMinuteSecond 
Go 
Exec(
'Create Function dbo.UFN_HourMinuteSecond 
(
@StartDateTime DateTime, 
@EndDateTime DateTime 
) Returns Varchar(10) 
As 
Begin 

Declare @Seconds Int, 
@Minute Int, 
@Hour Int, 
@Elapsed Varchar(10) 

Select @Seconds = ABS(DateDiff(SECOND ,@StartDateTime,@EndDateTime)) 

If @Seconds >= 60 
Begin 
select @Minute = @Seconds/60 
select @Seconds = @Seconds%60 

If @Minute >= 60 
begin 
select @hour = @Minute/60 
select @Minute = @Minute%60 
end 

Else 
Goto Final 
End 

Final: 
Select @Hour = Isnull(@Hour,0), @Minute = IsNull(@Minute,0), @Seconds =    IsNull(@Seconds,0) 
select @Elapsed = Cast(@Hour as Varchar) + '':'' + Cast(@Minute as Varchar) + '':'' +  Cast(@Seconds as Varchar) 

Return (@Elapsed) 
End' 
) 
4

Ci sono un certo numero di modi di guardare la differenza data, e più quando si confrontano data/orari. Ecco quello che io uso per ottenere la differenza tra due date formattate come "HH: MM: SS":

ElapsedTime AS 
     RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate)  /3600 AS VARCHAR(2)), 2) + ':' 
    + RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 3600/ 60 AS VARCHAR(2)), 2) + ':' 
    + RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 60  AS VARCHAR(2)), 2) 

Ho usato questo per una colonna calcolata, ma si potrebbe banalmente riscrivere come un calcolo UDF o una query.Si noti che questa logica arrotonda i secondi frazionari; 00: 00,00 a 00: 00,99 è considerato zero secondi e visualizzato come "00:00:00".

Se si prevede che i periodi possono essere più di tempo di pochi giorni, il codice passa a D: HH: MM: SS quando necessario:

ElapsedTime AS 
    CASE WHEN DATEDIFF(S, StartDate, EndDate) >= 359999 
     THEN 
          CAST(DATEDIFF(S, StartDate, EndDate)/86400  AS VARCHAR(7)) + ':' 
      + RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 86400/3600 AS VARCHAR(2)), 2) + ':' 
      + RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 3600/ 60 AS VARCHAR(2)), 2) + ':' 
      + RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 60  AS VARCHAR(2)), 2) 
     ELSE 
       RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate)  /3600 AS VARCHAR(2)), 2) + ':' 
      + RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 3600/ 60 AS VARCHAR(2)), 2) + ':' 
      + RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 60  AS VARCHAR(2)), 2) 
     END 
0
declare @dt1 datetime='2012/06/13 08:11:12', @dt2 datetime='2012/06/12 02:11:12' 

select CAST((@[email protected]) as time(0)) 
5

posso citare quattro funzioni importanti di MS SQL Server che può essere molto utile:

1) la funzione DATEDIFF() è responsabile per calcolare le differenze tra due date, il risultato potrebbe essere "settimana anno giorno quarto mese dayofyear ora minuto secondo millisecondo microsecondo nanosecondo 012.309.368,644 mila", specificato nel primo parametro (datepart):

select datediff(day,'1997-10-07','2011-09-11') 

2) È possibile utilizzare la funzione GETDATE() per ottenere il tempo reale e calcolare le differenze di una data e la data effettiva:

select datediff(day,'1997-10-07', getdate()) 

3) Un'altra funzione importante è DATEADD(), utilizzata per convertire un valore in datetime utilizzando lo stesso datario del datediff, che è possibile aggiungere (con valori positivi) o sottrarre (con valori negativi) a una data base:

select DATEADD(day, 45, getdate()) -- actual datetime adding 45 days 
select DATEADD( s,-638, getdate()) -- actual datetime subtracting 10 minutes and 38 seconds 

4) La funzione CONVERT() è stato fatto per formattare la data come avete bisogno, non è funzione parametrica, ma è possibile utilizzare una parte del risultato per formattare il risultato come avete bisogno:

select convert( char(8), getdate() , 8) -- part hh:mm:ss of actual datetime 
select convert( varchar, getdate() , 112) -- yyyymmdd 
select convert(char(10), getdate() , 20) -- yyyy-mm-dd limited by 10 characters 

DATETIME freddo calcolata in pochi secondi e uno risultato interessante mescolando questi quattro funzione è di mostrare una differenza formattato um ore, minuti e secondi (hh: mm: ss) tra due date:

declare @date1 datetime, @date2 datetime 
set @date1=DATEADD(s,-638,getdate()) 
set @date2=GETDATE() 

select convert(char(8),dateadd(s,datediff(s,@date1,@date2),'1900-1-1'),8) 

... il risultato è 00:10:38 (638s = 600s + 38s = 10 minuti e 38 secondi)

altro esempio:

select distinct convert(char(8),dateadd(s,datediff(s, CRDATE , GETDATE()),'1900-1-1'),8) from sysobjects order by 1 
0

PRINT DATEDIFF (seconda, '2010- 01-22 15: 29: 55.090 ',' 2010-01-22 15: 30: 09.153 ')

0
select 
datediff(millisecond,'2010-01-22 15:29:55.090','2010-01-22 15:30:09.153')/1000.0 as Secs 

result: 
Secs 
14.063 

Ho solo pensato di parlarne.

1

La seguente query dovrebbe fornire esattamente le informazioni che stai cercando.

select datediff(second, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153') 

Ecco il collegamento da MSDN per ciò che tutto ciò che si può fare con la funzione datediff. https://msdn.microsoft.com/en-us/library/ms189794.aspx

0

CREATE getDateDiffHours FUNCTION (@fdate AS datetime, @ TDate come datetime) RETURNS varchar (50) AS BEGIN DECLARE @cnt int DECLARE @cntDate datetime DECLARE @dayDiff int DECLARE @dayDiffWk int DECLARE @hrsDiff decimale (18)

DECLARE @markerFDate datetime 
DECLARE @markerTDate datetime 

DECLARE @fTime int 
DECLARE @tTime int 


DECLARE @nfTime varchar(8) 
DECLARE @ntTime varchar(8) 

DECLARE @nfdate datetime 
DECLARE @ntdate datetime 

------------------------------------- 
--DECLARE @fdate datetime 
--DECLARE @tdate datetime 

--SET @fdate = '2005-04-18 00:00:00.000' 
--SET @tdate = '2005-08-26 15:06:07.030' 
------------------------------------- 

DECLARE @tempdate datetime 

--setting weekends 
SET @fdate = dbo.getVDate(@fdate) 
SET @tdate = dbo.getVDate(@tdate) 
--RETURN @fdate 

SET @fTime = datepart(hh,@fdate) 
SET @tTime = datepart(hh,@tdate) 
--RETURN @fTime 
if datediff(hour,@fdate, @tdate) <= 9 

     RETURN(convert(varchar(50),0) + ' Days ' + convert(varchar(50),datediff(hour,@fdate, @tdate))) + ' Hours' 
else 
--setting working hours 
SET @nfTime = dbo.getV00(convert(varchar(2),datepart(hh,@fdate))) + ':' +dbo.getV00(convert(varchar(2),datepart(mi,@fdate))) + ':'+ dbo.getV00(convert(varchar(2),datepart(ss,@fdate))) 
SET @ntTime = dbo.getV00(convert(varchar(2),datepart(hh,@tdate))) + ':' +dbo.getV00(convert(varchar(2),datepart(mi,@tdate))) + ':'+ dbo.getV00(convert(varchar(2),datepart(ss,@tdate))) 

IF @fTime > 17 
begin 
    set @nfTime = '17:00:00' 
end 
else 
begin 
    IF @fTime < 8 
     set @nfTime = '08:00:00' 
end 

IF @tTime > 17 
begin 
    set @ntTime = '17:00:00' 
end 
else 
begin 
    IF @tTime < 8 
     set @ntTime = '08:00:00' 
end 



-- used for working out whole days 

SET @nfdate = dateadd(day,1,@fdate) 

SET @ntdate = @tdate 
SET @nfdate = convert(varchar,datepart(yyyy,@nfdate)) + '-' + convert(varchar,datepart(mm,@nfdate)) + '-' + convert(varchar,datepart(dd,@nfdate)) 
SET @ntdate = convert(varchar,datepart(yyyy,@ntdate)) + '-' + convert(varchar,datepart(mm,@ntdate)) + '-' + convert(varchar,datepart(dd,@ntdate)) 
SET @cnt = 0 
SET @dayDiff = 0 
SET @cntDate = @nfdate 
SET @dayDiffWk = convert(decimal(18,2),@[email protected]) 

--select @nfdate,@ntdate 

WHILE @cnt < @dayDiffWk 
BEGIN 
    IF (NOT DATENAME(dw, @cntDate) = 'Saturday') AND (NOT DATENAME(dw, @cntDate) = 'Sunday') 
    BEGIN 
     SET @dayDiff = @dayDiff + 1 
    END 
    SET @cntDate = dateadd(day,1,@cntDate) 
    SET @cnt = @cnt + 1 
END 

--SET @dayDiff = convert(decimal(18,2),@[email protected]) --datediff(day,@nfdate,@ntdate) 
--SELECT @dayDiff 

set @fdate = convert(varchar,datepart(yyyy,@fdate)) + '-' + convert(varchar,datepart(mm,@fdate)) + '-' + convert(varchar,datepart(dd,@fdate)) + ' ' + @nfTime 
set @tdate = convert(varchar,datepart(yyyy,@tdate)) + '-' + convert(varchar,datepart(mm,@tdate)) + '-' + convert(varchar,datepart(dd,@tdate)) + ' ' + @ntTime 

set @markerFDate = convert(varchar,datepart(yyyy,@fdate)) + '-' + convert(varchar,datepart(mm,@fdate)) + '-' + convert(varchar,datepart(dd,@fdate)) + ' ' + '17:00:00' 
set @markerTDate = convert(varchar,datepart(yyyy,@tdate)) + '-' + convert(varchar,datepart(mm,@tdate)) + '-' + convert(varchar,datepart(dd,@tdate)) + ' ' + '08:00:00' 

--select @fdate,@tdate 
--select @markerFDate,@markerTDate 

set @hrsDiff = convert(decimal(18,2),datediff(hh,@fdate,@markerFDate)) 

--select @hrsDiff 
set @hrsDiff = @hrsDiff + convert(int,datediff(hh,@markerTDate,@tdate)) 

--select @fdate,@tdate 

IF convert(varchar,datepart(yyyy,@fdate)) + '-' + convert(varchar,datepart(mm,@fdate)) + '-' + convert(varchar,datepart(dd,@fdate)) = convert(varchar,datepart(yyyy,@tdate)) + '-' + convert(varchar,datepart(mm,@tdate)) + '-' + convert(varchar,datepart(dd,@tdate)) 
BEGIN 
    --SET @hrsDiff = @hrsDiff - 9 
    Set @hrsdiff = datediff(hour,@fdate,@tdate) 
END 

--select FLOOR((@hrsDiff/9)) 

IF (@hrsDiff/9) > 0 
BEGIN 
    SET @dayDiff = @dayDiff + FLOOR(@hrsDiff/9) 
    SET @hrsDiff = @hrsDiff - FLOOR(@hrsDiff/9)*9 
END 

--select convert(varchar(50),@dayDiff) + ' Days ' + convert(varchar(50),@hrsDiff) + ' Hours' 

RETURN(convert(varchar(50),@dayDiff) + ' Days ' + convert(varchar(50),@hrsDiff)) + ' Hours' 

END

+0

Puoi spiegare il tuo codice in base alla domanda? – user7294900

0

Sol-1:

select 
    StartTime 
    , EndTime 
    , CONVERT(NVARCHAR,(EndTime-StartTime), 108) as TimeDiff 
from 
    [YourTable] 

Sol-2:

select 
    StartTime 
    , EndTime 
    , DATEDIFF(hh, StartTime, EndTime) 
    , DATEDIFF(mi, StartTime, EndTime) % 60 
from 
    [YourTable] 

Sol-3:

select 
    DATEPART(hour,[EndTime]-[StartTime]) 
    , DATEPART(minute,[EndTime]-[StartTime]) 
from 
    [YourTable] 

Datepart funziona meglio

0

Controlli prego sotto trucco per trovare la differenza di data tra due date

DATEDIFF(DAY,ordr.DocDate,RDR1.U_ProgDate) datedifff 

cui è possibile modificare secondo il vostro requisito come si desidera differenza di giorni o mesi o un anno o di tempo.

Problemi correlati