Home > Database > Mysql Tutorial > body text

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

王林
Release: 2023-08-23 16:53:32
forward
1037 people have browsed it

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)
Copy after login

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)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!