Home >Database >Mysql Tutorial >How can we return the difference in year, month and day between two date values ​​using a function?

How can we return the difference in year, month and day between two date values ​​using a function?

王林
王林forward
2023-08-23 16:53:321105browse

How can we return the difference in year, month and day between two date values ​​using a function?

We can create a function which accepts a date value as parameter and returns the difference of year, month and day as shown below

mysql> CREATE FUNCTION date_difference(Date1 DATE, date2 DATE) RETURNS VARCHAR(30)
   -> RETURN CONCAT(
   -> @years := TIMESTAMPDIFF(YEAR, date1, date2),IF (@years = 1, ' year, ', ' years, '),
   -> @months := TIMESTAMPDIFF(MONTH, DATE_ADD(date1, INTERVAL @years YEAR), date2),IF (@months = 1, ' month, ', ' months, '),
   -> @days := TIMESTAMPDIFF(DAY, DATE_ADD(date1, INTERVAL @years * 12 + @months MONTH), date2),IF (@days = 1, ' day', ' days')) ;
   Query OK, 0 rows affected (0.00 sec)

Now, add the date value Passed as argument to function date_difference

mysql> Select date_difference('2015-11-16','2016-12-17') AS Difference;
+------------------------+
| Difference             |
+------------------------+
| 1 year, 1 month, 1 day |
+------------------------+
1 row in set (0.00 sec)

The above result set gives the difference between the two specified dates as argument to the function.

The above is the detailed content of How can we return the difference in year, month and day between two date values ​​using a function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete