Name already in use
sql-docs / docs / t-sql / functions / datediff-transact-sql.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
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
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.
int
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.
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.
If startdate and enddate have different year values, but they have the same calendar week values, DATEDIFF will return 0 for datepart week.
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.
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.
B. Specifying user-defined variables for startdate and enddate
In this example, user-defined variables serve as arguments for startdate and enddate.
C. Specifying scalar system functions for startdate and enddate
This example uses scalar system functions as arguments for startdate and enddate.
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.
E. Specifying constants for startdate and enddate
This example uses character constants as arguments for startdate and enddate.
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.
G. Specifying ranking functions for startdate
This example uses a ranking function as an argument for startdate.
H. Specifying an aggregate window function for startdate
This example uses an aggregate window function as an argument for startdate.
I. Finding difference between startdate and enddate as date parts strings
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.
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.
L. Specifying constants for startdate and enddate
This example uses character constants as arguments for startdate and enddate.
M. Specifying ranking functions for startdate
This example uses a ranking function as an argument for startdate.
N. Specifying an aggregate window function for startdate
This example uses an aggregate window function as an argument for startdate.
Функция DATEDIFF стр. 2

Консоль
Результат – 100 минут.
В запросе используется стандартное представление даты (ISO) в виде текстовой строки ‘yyyy-mm-ddThh:mm:ss’, которое не зависит ни от локальных настроек сервера, ни и от самого сервера.
MySQL
Функция DATEDIFF есть и в MySQL, однако она имеет совсем другой смысл. DATEDIFF вычисляет число дней между двумя датами, являющихся аргументами этой функции. При этом если дата представлена в формате дата-время, используется только составляющая даты. Поэтому все три нижепредставленных запроса дадут один и тот же результат -1. Положительный результат будет получен, если первый аргумент больше второго.
Один день мы получим даже в случае, если интервал между датами составляет все одну секунду:
Решение же нашей задачи можно получить при помощи другой встроенной функции – TIMESTAMPDIFF, которая аналогичная функции DATEDIFF в
Язык структурированных запросов) — универсальный компьютерный язык, применяемый для создания, модификации и управления данными в реляционных базах данных. SQL Server:
PostgreSQL
В PostgreSQL нет функции, подобной DATEDIFF (SQL Server) или TIMESTAMPDIFF (MySQL). Поэтому для решения задачи можно применить следующую последовательность действий:
- представить разность между двумя датами интервалом;
- посчитать число секунд в интервале;
- поделить полученное на шаге 2 значение на 60, чтобы выразить результат в минутах.
Для получения интервала можно взять разность двух значений темпорального типа, При этом требуется явное преобразование типа:
Результат — «01:40:00», который есть не что иное, как один час и сорок минут.
Можно также воспользоваться встроенной функцией AGE , которая выполняет заодно неявное преобразование типа своих аргументов:
Для получения числа секунд в интервале воспользуемся функцией
Значение интервала представим последним способом как наиболее коротким. Для получения окончательного решения задачи поделим полученный результат на 60:
В данном случае мы имеем результат, выраженный целым числом, поскольку оба значения времени в задаче не содержали секунд. В противном случае, будет получено десятичное число, например: 99.75:
Oracle
Oracle тоже не имеет в своем арсенале функции типа DATEDIFF. Кроме того, Oracle не поддерживает стандартное текстовое представление даты/времени.
Мы можем посчитать интервал в минутах, приняв во внимание, что разность дат (значений типа date ) в Oracle дает в результате число дней (суток). Тогда для вычисления интервала в минутах нужно просто разность дат умножить на 24 (число часов в сутках), а затем на 60 (число минут в часе):
How to get the number of days of difference between two dates on MySQL?
I need to get the number of days contained within a couple of dates on MySQL.
- Check in date is 12-04-2010
- Check out date 15-04-2010
The day difference would be 3.
![]()
8 Answers 8
What about the DATEDIFF function ?
Quoting the manual’s page :
DATEDIFF() returns expr1 – expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation
In your case, you’d use :
But note the dates should be written as YYYY-MM-DD , and not DD-MM-YYYY like you posted.
Note if you want to count FULL 24h days between 2 dates, datediff can return wrong values for you.
As documentation states:
Only the date parts of the values are used in the calculation.
which results in
select datediff(‘2016-04-14 11:59:00’, ‘2016-04-13 12:00:00’)
returns 1 instead of expected 0.
Solution is using select timestampdiff(DAY, ‘2016-04-13 11:00:01’, ‘2016-04-14 11:00:00’); (note the opposite order of arguments compared to datediff).
- select timestampdiff(DAY, ‘2016-04-13 11:00:01’, ‘2016-04-14 11:00:00’); returns 0
- select timestampdiff(DAY, ‘2016-04-13 11:00:00’, ‘2016-04-14 11:00:00’); returns 1
- select timestampdiff(DAY, ‘2016-04-13 11:00:00’, now()); returns how many full 24h days has passed since 2016-04-13 11:00:00 until now.
Hope it will help someone, because at first it isn’t much obvious why datediff returns values which seems to be unexpected or wrong.