Home >Database >Mysql Tutorial >How can we create a MySQL function to find the duration in year, month, day, hour, minutes and seconds?

How can we create a MySQL function to find the duration in year, month, day, hour, minutes and seconds?

王林
王林forward
2023-09-10 21:33:111051browse

我们如何创建一个 MySQL 函数来找出年、月、日、小时、分钟和秒的持续时间?

Below is a MySQL function that calculates the duration in years, months, days, hours, minutes and seconds between two dates.

mysql> DROP FUNCTION IF EXISTS Duration;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> DROP FUNCTION IF EXISTS Label123;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> DELIMITER //
mysql> CREATE FUNCTION Duration( dtd1 datetime, dtd2 datetime ) RETURNS CHAR(128)
   -> BEGIN
   -> DECLARE yyr,mon,mmth,dy,ddy,hhr,m1,ssc,t1 BIGINT;
   -> DECLARE dtmp DATETIME;
   -> DECLARE t0 TIMESTAMP;
   -> SET yyr = TIMESTAMPDIFF(YEAR,dtd1,dtd2);
   -> SET mon = TIMESTAMPDIFF(MONTH,dtd1,dtd2);
   -> SET mmth = mon MOD 12;
   -> SET dtmp = ADDDATE(dtd1, interval mon MONTH);
   -> SET dy = TIMESTAMPDIFF(DAY,dtd1,dtd2);
   -> SET ddy = TIMESTAMPDIFF(DAY,dtmp,dtd2);
   -> SET t0 = TIMESTAMPADD(DAY,dy,dtd1);
   -> SET t1 = TIME_TO_SEC(TIMEDIFF(dtd2,t0));
   -> SET hhr = FLOOR(t1/3600);
   -> SET m1 = FLOOR(t1/60) - 60*hhr;
   -> SET ssc = t1 - 3600*hhr - 60*m1;
   -> RETURN CONCAT( Label123(yyr,'year'), Label123(mmth,'month'),
   ->    label123(ddy,'day'), Label123(hhr,'hour'),
   ->    Label123(m1,'min'), Label123(ssc,'sec')
   -> );
   -> END;
   -> //
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE FUNCTION Label123( ival int, clabel char(16) ) RETURNS VARCHAR(24)
   -> RETURN Concat( ival, ' ', clabel, If(ival=1,' ','s ') ); //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

mysql> Select Duration('2000-08-04 06:09:46', '2011-07-01 05:05:36')AS 'Duration';
+-----------------------------------------------------+
| Duration                                            |
+-----------------------------------------------------+
| 10 years 10 months 26 days 22 hours 55 mins 50 secs |
+-----------------------------------------------------+
1 row in set (0.00 sec)

The above is the detailed content of How can we create a MySQL function to find the duration in year, month, day, hour, minutes and seconds?. 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