> ## Documentation Index
> Fetch the complete documentation index at: /documents/llms.txt
> Use this file to discover all available pages before exploring further.

# date_diff

> 根据指定的时间单位返回两个日期的差值。

根据指定的时间单位返回两个日期的差值。该函数按照 `unit` 指定的时间单位返回 `expr1 - expr2` 的差值。比如 `date_diff('second', '2010-11-30 23:59:59', '2010-11-30 20:58:59')` 以秒为单位返回这两个日期的差值。

该函数从 3.1 版本开始支持。与 [datediff](/documents/cn/4.2/sql-reference/sql-functions/date-time-functions/datediff.md) 的区别在于 datediff 不支持指定时间单位 `unit`。

## 语法

```Haskell theme={null}
BIGINT DATE_DIFF(VARCHAR unit, DATETIME expr1, DATETIME expr2)
```

## 参数说明

* `unit`：差值的时间单位，必填。`unit` 的取值必须是 `year`, `quarter`, `month`, `week`，`day`，`hour`，`minute`，`second`，`millisecond`。
* `expr1`，`expr2`：要进行比较的两个日期值，必填。支持的数据类型为 DATETIME 和 DATE。

## 返回值说明

返回 BIGINT 类型的值。

## 使用说明

* 如果 `expr1` 早于 `expr2`，返回负值。
* 如果 `unit` 超出指定的单位，返回报错。
* 如果任一输入参数为 NULL，返回 NULL。
* 如果指定的日期不存在，比如 `2022-11-31`，返回 NULL。

## 示例

```Plain Text theme={null}
mysql> select date_diff('second', '2010-11-30 23:59:59', '2010-11-30 20:58:59');
+-------------------------------------------------------------------+
| date_diff('second', '2010-11-30 23:59:59', '2010-11-30 20:58:59') |
+-------------------------------------------------------------------+
|                                                             10860 |

mysql> select date_diff('minute', '2010-11-30 23:59:59', '2010-11-30 20:58:59');
+-------------------------------------------------------------------+
| date_diff('minute', '2010-11-30 23:59:59', '2010-11-30 20:58:59') |
+-------------------------------------------------------------------+
|                                                               181 |
+-------------------------------------------------------------------+

mysql> select date_diff('hour', '2010-11-30 23:59:59', '2010-11-30 20:58:59');
+-----------------------------------------------------------------+
| date_diff('2010-11-30 23:59:59', '2010-11-30 20:58:59', 'hour') |
+-----------------------------------------------------------------+
|                                                              3  |
+-----------------------------------------------------------------+

mysql> select date_diff('millisecond', '2010-11-30 23:59:59', '2010-11-30 20:58:59');
+------------------------------------------------------------------------+
| date_diff('millisecond', '2010-11-30 23:59:59', '2010-11-30 20:58:59') |
+------------------------------------------------------------------------+
|                                                               10860000 |
+------------------------------------------------------------------------+
```

## 相关参考

[datediff](/documents/cn/4.2/sql-reference/sql-functions/date-time-functions/datediff.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.