MySQL TIMESTAMPDIFF() Function
In MySQL, the TIMESTAMPDIFF()
function returns the time interval between two datetimes.
TIMESTAMPDIFF()
Syntax
Here is the syntax of MySQL TIMESTAMPDIFF()
function:
TIMESTAMPDIFF(unit, datetime1, datetime2)
Parameters
unit
- Required. The unit of time interval, available values:
MICROSECOND
,SECOND
,MINUTE
,HOUR
,DAY
,WEEK
,MONTH
,QUARTER
,YEAR
. datetime1
- Required. A datetime value or expression.
datetime2
- Required. Another datetime value or expression.
Return value
The MySQL TIMESTAMPDIFF()
function returns the time interval between two dates/datetimes.
The TIMESTAMPDIFF()
function will return NULL
if any parameter is NULL
.
TIMESTAMPDIFF()
Examples
Here are some examples of the TIMESTAMPDIFF()
function.
SELECT
TIMESTAMPDIFF(YEAR, '2021-12-28', '2022-02-28'),
TIMESTAMPDIFF(MONTH, '2021-02-28', '2022-02-28'),
TIMESTAMPDIFF(MONTH, '2022-02-28', '2021-02-28')\G
TIMESTAMPDIFF(YEAR, '2021-12-28', '2022-02-28'): 0
TIMESTAMPDIFF(MONTH, '2021-02-28', '2022-02-28'): 12
TIMESTAMPDIFF(MONTH, '2022-02-28', '2021-02-28'): -12