mysql查詢兩個日期之間相差多少天?


需求描述:

  在mysql中,查看兩個日期之間相差多少天

操作過程:

1.通過datediff函數,查看兩個日期之間相差多少天

mysql> select datediff('2018-06-26','2018-06-25'),datediff('2018-06-20','2018-06-26');
+-------------------------------------+-------------------------------------+
| datediff('2018-06-26','2018-06-25') | datediff('2018-06-20','2018-06-26') |
+-------------------------------------+-------------------------------------+
|                                   1 |                                  -6 |
+-------------------------------------+-------------------------------------+
1 row in set (0.00 sec)

備注:datediff(expr1,expr2),一般返回的就是expr1-expr2的差值,結果可以是正數,也可以是負數.主要是兩個日期之間相差多少天.

2.帶有時分秒的表達式

mysql> select datediff('2018-06-26 22:00:00','2018-06-25'),datediff('2018-06-20','2018-06-26 21:00:00');
+----------------------------------------------+----------------------------------------------+
| datediff('2018-06-26 22:00:00','2018-06-25') | datediff('2018-06-20','2018-06-26 21:00:00') |
+----------------------------------------------+----------------------------------------------+
|                                            1 |                                           -6 |
+----------------------------------------------+----------------------------------------------+
1 row in set (0.00 sec)

備注:在日期計算中,如果存在時分秒的部分,是會被忽略的只對日期的部分進行計算即只對天計算.

 

文檔創建時間:2018年6月26日12:47:32

 

官方文檔參考:

DATEDIFF(expr1,expr2)

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. mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30'); -> 1 mysql> SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31'); -> -31


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM