Как найти разницу во времени sql

TIMEDIFF

Возвращает разницу во времени (datetime1 — datetime2) между DATETIME или TIME значениями. Результат возвращается в формате ЧЧ:ММ:СС.

TIMEDIFF(datetime1, datetime2)

Возвращает NULL, если одно из переданных значений равно NULL или оба значения имеют разный тип.

Примеры

SELECT TIMEDIFF('2022-12-05 18:00:00','2022-12-05 14:00:00')
SELECT TIMEDIFF('2022-12-05 18:00:00','2021-12-01 14:00:00')
SELECT TIMEDIFF('2022-12-05 14:00:00','2022-12-05 18:00:00')
SELECT TIMEDIFF('18:00:00','14:00:00')
SELECT TIMEDIFF('18:00:00','2022-12-05 14:00:00')
CREATE FUNCTION getDateDiffHours(@fdate AS datetime,@tdate as datetime)
RETURNS varchar (50)
AS
BEGIN
    DECLARE @cnt int
    DECLARE @cntDate datetime
    DECLARE @dayDiff int
    DECLARE @dayDiffWk int
    DECLARE @hrsDiff decimal(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),@ntdate-@nfdate)
    
    --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),@ntdate-@nfdate) --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

title description author ms.author ms.date ms.service ms.subservice ms.topic f1_keywords helpviewer_keywords dev_langs monikerRange

DATEDIFF (Transact-SQL)

Transact-SQL reference for the DATEDIFF function. Returns the numerical difference between a start and end date based on datepart.

markingmyname

maghan

07/18/2019

sql

t-sql

reference

DATEDIFF_TSQL

DATEDIFF

dates [SQL Server], functions

DATEDIFF function [SQL Server]

time [SQL Server], crossed boundaries

differences in date and time [SQL Server]

counting crossed date time boundaries [SQL Server]

date and time [SQL Server], DATEDIFF

dates [SQL Server], crossed boundaries

boundary differences date and time [SQL Server]

functions [SQL Server], time

functions [SQL Server], date and time

interval dates [SQL Server]

time [SQL Server], functions

crossing date time boundaries [SQL Server]

calculating dates times [SQL Server]

TSQL

>= aps-pdw-2016 || = azuresqldb-current || = azure-sqldw-latest || >= sql-server-2016 || >= sql-server-linux-2017 || = azuresqldb-mi-current

DATEDIFF (Transact-SQL)

[!INCLUDE sql-asdb-asdbmi-asa-pdw]

This function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified startdate and enddate.

See DATEDIFF_BIG (Transact-SQL) for a function that handles larger differences between the startdate and enddate values. See Date and Time Data Types and Functions (Transact-SQL) for an overview of all [!INCLUDEtsql] date and time data types and functions.

:::image type=»icon» source=»../../includes/media/topic-link-icon.svg» border=»false»::: Transact-SQL syntax conventions

Syntax

DATEDIFF ( datepart , startdate , enddate )  

[!INCLUDEsql-server-tsql-previous-offline-documentation]

Arguments

datepart
The units in which DATEDIFF reports the difference between the startdate and enddate. Commonly used datepart units include month or second.

The datepart value cannot be specified in a variable, nor as a quoted string like 'month'.

The following table lists all the valid datepart values. DATEDIFF accepts either the full name of the datepart, or any listed abbreviation of the full name.

datepart name datepart abbreviation
year y, yy, yyyy
quarter qq, q
month mm, m
dayofyear dy
day dd, d
week wk, ww
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns

[!NOTE]
Each specific datepart name and abbreviations for that datepart name will return the same value.

startdate
An expression that can resolve to one of the following values:

  • date
  • datetime
  • datetimeoffset
  • datetime2
  • smalldatetime
  • time

Use four-digit years to avoid ambiguity. See Configure the two digit year cutoff Server Configuration Option for information about two-digit year values.

enddate
See startdate.

Return Type

int

Return Value

The int difference between the startdate and enddate, expressed in the boundary set by datepart.

For example, SELECT DATEDIFF(day, '2036-03-01', '2036-02-28'); returns -2, hinting that 2036 must be a leap year. This case means that if we start at startdate ‘2036-03-01’, and then count -2 days, we reach the enddate of ‘2036-02-28’.

For a return value out of range for int (-2,147,483,648 to +2,147,483,647), DATEDIFF returns an error. For millisecond, the maximum difference between startdate and enddate is 24 days, 20 hours, 31 minutes and 23.647 seconds. For second, the maximum difference is 68 years, 19 days, 3 hours, 14 minutes and 7 seconds.

If startdate and enddate are both assigned only a time value, and the datepart is not a time datepart, DATEDIFF returns 0.

DATEDIFF uses the time zone offset component of startdate or enddate to calculate the return value.

Because smalldatetime is accurate only to the minute, seconds and milliseconds are always set to 0 in the return value when startdate or enddate have a smalldatetime value.

If only a time value is assigned to a date data type variable, DATEDIFF sets the value of the missing date part to the default value: 1900-01-01. If only a date value is assigned to a variable of a time or date data type, DATEDIFF sets the value of the missing time part to the default value: 00:00:00. If either startdate or enddate have only a time part and the other only a date part, DATEDIFF sets the missing time and date parts to the default values.

If startdate and enddate have different date data types, and one has more time parts or fractional seconds precision than the other, DATEDIFF sets the missing parts of the other to 0.

datepart boundaries

The following statements have the same startdate and the same enddate values. Those dates are adjacent and they differ in time by a hundred nanoseconds (.0000001 second). The difference between the startdate and enddate in each statement crosses one calendar or time boundary of its datepart. Each statement returns 1.

SELECT DATEDIFF(year,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(quarter,     '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(month,       '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(dayofyear,   '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(day,         '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(week,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(hour,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(minute,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(second,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(microsecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

If startdate and enddate have different year values, but they have the same calendar week values, DATEDIFF will return 0 for datepart week.

Remarks

Use DATEDIFF in the SELECT <list>, WHERE, HAVING, GROUP BY and ORDER BY clauses.

DATEDIFF implicitly casts string literals as a datetime2 type. This means that DATEDIFF does not support the format YDM when the date is passed as a string. You must explicitly cast the string to a datetime or smalldatetime type to use the YDM format.

Specifying SET DATEFIRST has no effect on DATEDIFF. DATEDIFF always uses Sunday as the first day of the week to ensure the function operates in a deterministic way.

DATEDIFF may overflow with a precision of minute or higher if the difference between enddate and startdate returns a value that is out of range for int.

Examples

These examples use different types of expressions as arguments for the startdate and enddate parameters.

A. Specifying columns for startdate and enddate

This example calculates the number of day boundaries crossed between dates in two columns in a table.

CREATE TABLE dbo.Duration  
    (startDate datetime2, endDate datetime2);  
    
INSERT INTO dbo.Duration(startDate, endDate)  
    VALUES ('2007-05-06 12:10:09', '2007-05-07 12:10:09');  
    
SELECT DATEDIFF(day, startDate, endDate) AS 'Duration'  
    FROM dbo.Duration;  
-- Returns: 1  

B. Specifying user-defined variables for startdate and enddate

In this example, user-defined variables serve as arguments for startdate and enddate.

DECLARE @startdate DATETIME2 = '2007-05-05 12:10:09.3312722';  
DECLARE @enddate   DATETIME2 = '2007-05-04 12:10:09.3312722';   
SELECT DATEDIFF(day, @startdate, @enddate);  

C. Specifying scalar system functions for startdate and enddate

This example uses scalar system functions as arguments for startdate and enddate.

SELECT DATEDIFF(millisecond, GETDATE(), SYSDATETIME());  

D. Specifying scalar subqueries and scalar functions for startdate and enddate

This example uses scalar subqueries and scalar functions as arguments for startdate and enddate.

USE AdventureWorks2012;  
GO  
SELECT DATEDIFF(day,
    (SELECT MIN(OrderDate) FROM Sales.SalesOrderHeader),  
    (SELECT MAX(OrderDate) FROM Sales.SalesOrderHeader));  

E. Specifying constants for startdate and enddate

This example uses character constants as arguments for startdate and enddate.

SELECT DATEDIFF(day,
   '2007-05-07 09:53:01.0376635',
   '2007-05-08 09:53:01.0376635');  

F. Specifying numeric expressions and scalar system functions for enddate

This example uses a numeric expression, (GETDATE() + 1), and scalar system functions GETDATE and SYSDATETIME, as arguments for enddate.

USE AdventureWorks2012;  
GO  
SELECT DATEDIFF(day, '2007-05-07 09:53:01.0376635', GETDATE() + 1)
    AS NumberOfDays  
    FROM Sales.SalesOrderHeader;  
GO  
USE AdventureWorks2012;  
GO  
SELECT
    DATEDIFF(
            day,
            '2007-05-07 09:53:01.0376635',
            DATEADD(day, 1, SYSDATETIME())
        ) AS NumberOfDays  
    FROM Sales.SalesOrderHeader;  
GO  

G. Specifying ranking functions for startdate

This example uses a ranking function as an argument for startdate.

USE AdventureWorks2012;  
GO  
SELECT p.FirstName, p.LastName  
    ,DATEDIFF(day, ROW_NUMBER() OVER (ORDER BY   
        a.PostalCode), SYSDATETIME()) AS 'Row Number'  
FROM Sales.SalesPerson s   
    INNER JOIN Person.Person p   
        ON s.BusinessEntityID = p.BusinessEntityID  
    INNER JOIN Person.Address a   
        ON a.AddressID = p.BusinessEntityID  
WHERE TerritoryID IS NOT NULL   
    AND SalesYTD <> 0;  

H. Specifying an aggregate window function for startdate

This example uses an aggregate window function as an argument for startdate.

USE AdventureWorks2012;  
GO  
SELECT soh.SalesOrderID, sod.ProductID, sod.OrderQty, soh.OrderDate,
    DATEDIFF(day, MIN(soh.OrderDate)   
        OVER(PARTITION BY soh.SalesOrderID), SYSDATETIME()) AS 'Total'  
FROM Sales.SalesOrderDetail sod  
    INNER JOIN Sales.SalesOrderHeader soh  
        ON sod.SalesOrderID = soh.SalesOrderID  
WHERE soh.SalesOrderID IN(43659, 58918);  
GO  

I. Finding difference between startdate and enddate as date parts strings

-- DOES NOT ACCOUNT FOR LEAP YEARS
DECLARE @date1 DATETIME, @date2 DATETIME, @result VARCHAR(100);
DECLARE @years INT, @months INT, @days INT,
    @hours INT, @minutes INT, @seconds INT, @milliseconds INT;

SET @date1 = '1900-01-01 00:00:00.000'
SET @date2 = '2018-12-12 07:08:01.123'

SELECT @years = DATEDIFF(yy, @date1, @date2)
IF DATEADD(yy, -@years, @date2) < @date1 
SELECT @years = @years-1
SET @date2 = DATEADD(yy, -@years, @date2)

SELECT @months = DATEDIFF(mm, @date1, @date2)
IF DATEADD(mm, -@months, @date2) < @date1 
SELECT @months=@months-1
SET @date2= DATEADD(mm, -@months, @date2)

SELECT @days=DATEDIFF(dd, @date1, @date2)
IF DATEADD(dd, -@days, @date2) < @date1 
SELECT @days=@days-1
SET @date2= DATEADD(dd, -@days, @date2)

SELECT @hours=DATEDIFF(hh, @date1, @date2)
IF DATEADD(hh, -@hours, @date2) < @date1 
SELECT @hours=@hours-1
SET @date2= DATEADD(hh, -@hours, @date2)

SELECT @minutes=DATEDIFF(mi, @date1, @date2)
IF DATEADD(mi, -@minutes, @date2) < @date1 
SELECT @minutes=@minutes-1
SET @date2= DATEADD(mi, -@minutes, @date2)

SELECT @seconds=DATEDIFF(s, @date1, @date2)
IF DATEADD(s, -@seconds, @date2) < @date1 
SELECT @seconds=@seconds-1
SET @date2= DATEADD(s, -@seconds, @date2)

SELECT @milliseconds=DATEDIFF(ms, @date1, @date2)

SELECT @result= ISNULL(CAST(NULLIF(@years,0) AS VARCHAR(10)) + ' years,','')
     + ISNULL(' ' + CAST(NULLIF(@months,0) AS VARCHAR(10)) + ' months,','')    
     + ISNULL(' ' + CAST(NULLIF(@days,0) AS VARCHAR(10)) + ' days,','')
     + ISNULL(' ' + CAST(NULLIF(@hours,0) AS VARCHAR(10)) + ' hours,','')
     + ISNULL(' ' + CAST(@minutes AS VARCHAR(10)) + ' minutes and','')
     + ISNULL(' ' + CAST(@seconds AS VARCHAR(10)) 
     + CASE
            WHEN @milliseconds > 0
                THEN '.' + CAST(@milliseconds AS VARCHAR(10)) 
            ELSE ''
       END 
     + ' seconds','')

SELECT @result

[!INCLUDEssResult]

118 years, 11 months, 11 days, 7 hours, 8 minutes and 1.123 seconds

Examples: [!INCLUDEssazuresynapse-md] and [!INCLUDEssPDW]

These examples use different types of expressions as arguments for the startdate and enddate parameters.

J. Specifying columns for startdate and enddate

This example calculates the number of day boundaries crossed between dates in two columns in a table.

CREATE TABLE dbo.Duration 
    (startDate datetime2, endDate datetime2);
    
INSERT INTO dbo.Duration (startDate, endDate)  
    VALUES ('2007-05-06 12:10:09', '2007-05-07 12:10:09');  
    
SELECT TOP(1) DATEDIFF(day, startDate, endDate) AS Duration  
    FROM dbo.Duration;  
-- Returns: 1  

K. Specifying scalar subqueries and scalar functions for startdate and enddate

This example uses scalar subqueries and scalar functions as arguments for startdate and enddate.

-- Uses AdventureWorks  
  
SELECT TOP(1) DATEDIFF(day, (SELECT MIN(HireDate) FROM dbo.DimEmployee),  
    (SELECT MAX(HireDate) FROM dbo.DimEmployee))   
FROM dbo.DimEmployee;  
  

L. Specifying constants for startdate and enddate

This example uses character constants as arguments for startdate and enddate.

-- Uses AdventureWorks  
  
SELECT TOP(1) DATEDIFF(day,
    '2007-05-07 09:53:01.0376635',
    '2007-05-08 09:53:01.0376635') FROM DimCustomer;  

M. Specifying ranking functions for startdate

This example uses a ranking function as an argument for startdate.

-- Uses AdventureWorks  
  
SELECT FirstName, LastName,
    DATEDIFF(day, ROW_NUMBER() OVER (ORDER BY   
        DepartmentName), SYSDATETIME()) AS RowNumber  
FROM dbo.DimEmployee;  

N. Specifying an aggregate window function for startdate

This example uses an aggregate window function as an argument for startdate.

-- Uses AdventureWorks  
  
SELECT FirstName, LastName, DepartmentName,
    DATEDIFF(year, MAX(HireDate)  
        OVER (PARTITION BY DepartmentName), SYSDATETIME()) AS SomeValue  
FROM dbo.DimEmployee  

See also

DATEDIFF_BIG (Transact-SQL)
CAST and CONVERT (Transact-SQL)

DATEDIFF() function :
This function in SQL Server is used to find the difference between the two specified dates.

Features :

  • This function is used to find the difference between the two given dates values.
  • This function comes under Date Functions.
  • This function accepts three parameters namely interval, first value of date, and second value of date.
  • This function can include time in the interval section and also in the date value section.

Syntax :

DATEDIFF(interval, date1, date2)

Parameter :
This method accepts three parameters as given below :

  • interval : It is the specified part which is to be returned. Moreover, the values of the interval can be as given below:
  1. year, yyyy, yy = Year, which is the specified year.
  2. quarter, qq, q = Quarter, which is the specified quarter.
  3. month, mm, m = month, which is the specified month.
  4. dayofyear, dy, y = Day of the year, which is the specified day of the year.
  5. day, dd, d = Day, which is the specified day.
  6. week, ww, wk = Week, which is the specified week.
  7. weekday, dw, w = Weekday, which is the specified week day.
  8. hour, hh = hour, which is the specified hour.
  9. minute, mi, n = Minute, which is the specified minute.
  10. second, ss, s = Second, which is the specified second.
  11. millisecond, ms = Millisecond, which is the specified millisecond.
  • date1, date2 : The two specified dates in order to find the difference between them.

Returns :
It returns the difference between the two specified dates.

Example-1 :
Using DATEDIFF() function and getting the difference between two values of dates, in years.

SELECT DATEDIFF(year, '2010/01/12', '2021/01/12');

Output :

11

Example-2 :
Using DATEDIFF() function and getting the difference between two values of dates, in months.

SELECT DATEDIFF(month, '2010/2/12', '2021/12/12');

Output :

142

Example-3 :
Using DATEDIFF() function and getting the negative difference between the two values of dates, in day.

SELECT DATEDIFF(day, '2021/2/1', '2010/12/12');

Output :

-3704

Example-4 :
Using DATEDIFF() function and getting the difference between the two values of dates which includes time as well, in hour.

SELECT DATEDIFF(hour, '2019/2/1 09:55', '2020/12/12 07:45');

Output :

16318

Example-5 :
Using DATEDIFF() function and getting the difference between the two values of dates using variables which includes time as well, in second.

DECLARE @date1 VARCHAR(50);
DECLARE @date2 VARCHAR(50);
SET @date1 = '2019/2/1 09:55:44';
SET @date2 = '2020/12/12 07:45:22';
SELECT DATEDIFF(second, @date1, @date2);

Output :

58744178

Application :
This function is used to find the difference between two specified values of date.

Last Updated :
18 Jan, 2021

Like Article

Save Article

Relational databases store information in table cells — in columns that describe aspects of an item and rows which tie together the columns. SQL elapsed-time calculations for DATE, DATETIME, and TIMESTAMP data types are done with DATEDIFF function, with the following syntax:

DATEDIFF( date_expression_1, date_expression_2 );

Any valid date or date-time values are acceptable. Only the date portion of DATETIME or TIMESTAMP values are used, regardless of any time portion..

For background context, please check out our SQL Dates & Times blog entry.

DATEDIFF Excludes The Ending Date

DATEDIFF returns the exclusive relationship of date_expression_1 to date_expression_2 (that is to say, not including the ending day). To be as clear on this oft-confusing point, the number of days between the first and third of January is:

SELECT
   DATEDIFF( '2021-01-03', '2021-01-01' )
   AS 'Days From 1 and 3 January' ;
Days From 1 and 3 January
2

DATEDIFF Between Dates

To get to Cinco de Mayo from New Year’s Day:

SELECT
  DATEDIFF( '2021-05-05', '2021-01-01' )
  AS "From New Year’s Day to Cinco de Mayo" ;
From New Year’s Day to Cinco de Mayo
124

It’s 124 days from New Year’s Day until Cinco de Mayo begins.

SELECT
  DATEDIFF( '2021-01-01', '2021-05-05' )
  AS "From Cinco de Mayo to New Year’s Day" ;
From Cinco de Mayo to New Year’s Day
-124

The negative number shows that New Year’s Day is 124 days before Cinco de Mayo.

DATEDIFF Ignores Time Information — Use TIMEDIFF

As its name suggests, DATEDIFF ignores any time portion supplied. The related function, TIMEDIFF, honors time portions, returning a sting with the difference, as shown here:

SELECT
  DATEDIFF('2000:01:01 00:00:01', '2000:01:01 00:00:00')
    AS 'DATEDIFF ignores time',
  TIMEDIFF('2000:01:01 00:00:01', '2000:01:01 00:00:00')
    AS 'TIMEDIFF honors time';
DATEDIFF ignores time TIMEDIFF honors time
0 00:00:01

Note that TIMEDIFF doesn’t calculate negative (before) times; instead it reports a misleading “bad time format” error if argument 2 is later than argument 1.

Using DATEDIFF To Shape Results

In addition to using DATEDIFF to output elapsed times, it’s useful for restricting rows returned from a SQL Select. In the following example DATEDIFF is used to filter a user’s orders to those which took more than ten days between ordering and shipment.

SELECT order, order_time, ship_time
FROM purchases
WHERE DATEDIFF(order_time, ship_time) > 10;  

Use TIMESTAMPDIFF For Specific Units of Time

DATEDIFF and TIMEDIFF are great if their output formats are what’s needed. TIMESTAMPDIFF is suited for specific units of elapsed time. The following example shows how to get a difference in each of the supported units:

SET @start = '2023-01-01 00:00:00';
SET @stop = '2023-12-31 23:59:59' ;
SELECT
  timestampdiff(MICROSECOND, @start, @stop) AS 'microseconds',
  timestampdiff(SECOND, @start, @stop) AS 'seconds',
  timestampdiff(MINUTE, @start, @stop) AS 'minutes',
  timestampdiff(HOUR, @start, @stop) AS 'hours',
  timestampdiff(DAY, @start, @stop) AS 'days',
  timestampdiff(WEEK, @start, @stop) AS 'weeks',
  timestampdiff(MONTH, @start, @stop) AS 'months',
  timestampdiff(QUARTER, @start, @stop) AS 'quarters',
  timestampdiff(YEAR, @start, @stop) AS 'years';
microseconds seconds minutes hours days weeks months quarters years
31535999000000 31535999 525599 8759 364 52 11 3 0

So Many Date and Time Functions

Because time is such a central part of our experience, there are many date and time functions available. The feature set and syntax vary by databases, so becoming familiar with the appropriate documentation is vital. This is the very lengthy MySQL Date and Time manual page.

Conclusion

We’ve expanded upon our SQL Dates & Times blog entry with examples of calculating the difference between dates and times with DATEDIFF, TIMEDIFF,  and TIMESTAMPDIFF, along with a quick aside on how to use these functions to shape the results set from a SQL Select statement.

Start Learning

To learn more about SQL, check out other SQL blog posts and enroll in our SQL Nanodegree program.

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти исполнительного директора
  • Как исправить бородавки
  • Как найти контроллер unifi в сети
  • Мастер файлы имеют неверный порядок wrye bash как исправить
  • Как найти вкладки в моем телефоне

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии