Sql как найти разницу в датах

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

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

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)

Summary: in this tutorial, you will learn how to use the SQL DATEDIFF() function to calculate the difference between two dates.

Syntax

To calculate the difference between two dates, you use the DATEDIFF()function. The following illustrates the syntax of the DATEDIFF() function in SQL Server:

DATEDIFF ( datepart , startdate , enddate )

Code language: SQL (Structured Query Language) (sql)

Arguments

datepart

The datepart is a part of the date in which you want the function to return. The following table illustrates the valid parts of date in SQL Server:

Valid Date Part Abbreviations
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns

startdate, enddate

The startdate and enddate are date literals or expressions from which you want to find the difference.

Return

The DATEDIFF() function returns an integer value with the unit specified by the datepart argument.

Examples

The following example returns the number of year between two dates:

SELECT DATEDIFF(year,'2015-01-01','2018-01-01');

Code language: SQL (Structured Query Language) (sql)

Here is the result:

3

Code language: SQL (Structured Query Language) (sql)

To get the number of month or day, you change the first argument to month or day as shown below:

SELECT DATEDIFF(month,'2015-01-01','2018-01-01'), DATEDIFF(day,'2015-01-01','2018-01-01');

Code language: SQL (Structured Query Language) (sql)

The following shows the result:

m d ----------- ----------- 36 1096

Code language: SQL (Structured Query Language) (sql)

Notice that the DATEDIFF() function takes the leap year into account. As shown clearly in the result, because 2016 is the leap year, the difference in days between two dates is 2×365 + 366 = 1096.

The following example illustrates how to use the DATEDIFF() function to calculate the difference in hours between two DATETIME values:

SELECT DATEDIFF(hour,'2015-01-01 01:00:00','2015-01-01 03:00:00');

Code language: SQL (Structured Query Language) (sql)

The result is:

2

Code language: SQL (Structured Query Language) (sql)

Consider the following example:

SELECT DATEDIFF(hour,'2015-01-01 01:00:00','2015-01-01 03:45:00');

Code language: SQL (Structured Query Language) (sql)

It also returns two because the DATEDIFF() function returns an integer only. In this case, it truncated the minute part and only consider the hour part.

2

Code language: SQL (Structured Query Language) (sql)

The following example shows how to use the DATEDIFF() function to calculate the year of services of employees up to January 1st, 2018:

SELECT first_name, last_name, DATEDIFF(year, hire_date, '2018-01-01') year_of_services FROM employees;

Code language: SQL (Structured Query Language) (sql)

DATEDIFF in MySQL

Unlike SQL Server, MySQL has a slightly different DATEDIFF() function syntax:

DATEDIFF(startdate,enddate)

Code language: SQL (Structured Query Language) (sql)

MySQL only returns the difference between two dates in days. It ignores all the time part of the date in the calculation. See the following example:

SELECT DATEDIFF('2018-08-09','2018-08-18');

Code language: SQL (Structured Query Language) (sql)

The result is nine days:

9

Code language: SQL (Structured Query Language) (sql)

In this tutorial, you have learned how to use the SQL DATEDIFF() function to calculate the difference between two dates.

Was this tutorial helpful ?

  • GETDATE: возвращает текущую локальную дату и время на основе системных часов в виде объекта datetime

    SELECT GETDATE()	-- 2017-07-28 21:34:55.830
  • GETUTCDATE: возвращает текущую локальную дату и время по гринвичу (UTC/GMT) в виде объекта datetime

    SELECT GETUTCDATE()		-- 2017-07-28 18:34:55.830
  • SYSDATETIME: возвращает текущую локальную дату и время на основе системных часов, но отличие от GETDATE состоит в том, что
    дата и время возвращаются в виде объекта datetime2

    SELECT SYSDATETIME()		-- 2017-07-28 21:02:22.7446744
  • SYSUTCDATETIME: возвращает текущую локальную дату и время по гринвичу (UTC/GMT) в виде объекта
    datetime2

    SELECT SYSUTCDATETIME()		-- 2017-07-28 18:20:27.5202777
  • SYSDATETIMEOFFSET: возвращает объект datetimeoffset(7), который содержит дату и время относительно
    GMT

    SELECT SYSDATETIMEOFFSET()		-- 2017-07-28 21:02:22.7446744 +03:00
  • DAY: возвращает день даты, который передается в качестве параметра

    SELECT DAY(GETDATE())		-- 28
  • MONTH: возвращает месяц даты

    SELECT MONTH(GETDATE())		-- 7
  • YEAR: возвращает год из даты

    SELECT YEAR(GETDATE())		-- 2017
  • DATENAME: возвращает часть даты в виде строки. Параметр выбора части даты передается в качестве первого параметра, а сама дата передается в
    качестве второго параметра:

    SELECT DATENAME(month, GETDATE())		-- July

    Для определения части даты можно использовать следующие параметры (в скобках указаны их сокращенные версии):

    • year (yy, yyyy): год

    • quarter (qq, q): квартал

    • month (mm, m): месяц

    • dayofyear (dy, y): день года

    • day (dd, d): день месяца

    • week (wk, ww): неделя

    • weekday (dw): день недели

    • hour (hh): час

    • minute (mi, n): минута

    • second (ss, s): секунда

    • millisecond (ms): миллисекунда

    • microsecond (mcs): микросекунда

    • nanosecond (ns): наносекунда

    • tzoffset (tz): смешение в минутах относительно гринвича (для объекта datetimeoffset)

  • DATEPART: возвращает часть даты в виде числа. Параметр выбора части даты передается в качестве первого параметра (используются те же параметры, что и для
    DATENAME), а сама дата передается в качестве второго параметра:

    SELECT DATEPART(month, GETDATE())		-- 7
  • DATEADD: возвращает дату, которая является результатом сложения числа к определенному компоненту даты. Первый параметр представляет компонент даты, описанный выше для функции DATENAME. Второй параметр – добавляемое количество. Третий параметр – сама дата, к которой надо сделать прибавление:

    SELECT DATEADD(month, 2, '2017-7-28')		-- 2017-09-28 00:00:00.000
    SELECT DATEADD(day, 5, '2017-7-28')		-- 2017-08-02 00:00:00.000
    SELECT DATEADD(day, -5, '2017-7-28')		-- 2017-07-23 00:00:00.000
    

    Если добавляемое количество представляет отрицательное число, то фактически происходит уменьшение даты.

  • DATEDIFF: возвращает разницу между двумя датами. Первый параметр – компонент даты, который указывает, в каких единицах стоит измерять
    разницу. Второй и третий параметры – сравниваемые даты:

    SELECT DATEDIFF(year, '2017-7-28', '2018-9-28')		-- разница 1 год
    SELECT DATEDIFF(month, '2017-7-28', '2018-9-28')	-- разница 14 месяцев
    SELECT DATEDIFF(day, '2017-7-28', '2018-9-28')		-- разница 427 дней
    
  • TODATETIMEOFFSET: возвращает значение datetimeoffset, которое является результатом сложения временного
    смещения с объектом datetime2

    SELECT TODATETIMEOFFSET('2017-7-28 01:10:22', '+03:00')
    
  • SWITCHOFFSET: возвращает значение datetimeoffset, которое является результатом сложения временного
    смещения с другим объектом datetimeoffset

    SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), '+02:30')
  • EOMONTH: возвращает дату последнего дня для месяца, который используется в переданной в качестве параметра дате.

    SELECT EOMONTH('2017-02-05')	-- 2017-02-28
    SELECT EOMONTH('2017-02-05', 3)	-- 2017-05-31
    

    В качестве необязательного второго параметра можно передавать количество месяцев, которые необходимо прибавить к дате. Тогда последний день месяца будет вычисляться для новой даты.

  • DATEFROMPARTS: по году, месяцу и дню создает дату

    SELECT DATEFROMPARTS(2017, 7, 28)		-- 2017-07-28
  • ISDATE: проверяет, является ли выражение датой. Если является, то возвращает 1, иначе возвращает 0.

    SELECT ISDATE('2017-07-28')		-- 1
    SELECT ISDATE('2017-28-07')		-- 0
    SELECT ISDATE('28-07-2017')		-- 0
    SELECT ISDATE('SQL')			-- 0
    
  • В качестве примера использования функций можно привести создание таблицы заказов, которая содержит дату заказа:

    Выражение DEFAULT GETDATE() указывает, что если при добавлении данных не передается дата, то она автоматически вычисляется с помощью функции GETDATE().

    Добавить комментарий