I have two time column in a table name is start_time and end_time.
I need difference between these tile. e.g. start_time = 18:40:00
and end_time = 20:50:00
.
output will be 2 hours 10 minutes.
I have two time column in a table name is start_time and end_time.
I need difference between these tile. e.g. start_time = 18:40:00
and end_time = 20:50:00
.
output will be 2 hours 10 minutes.
Use TIMEDIFF
function of MySQL
SELECT
TIMEDIFF(end_time,start_time) AS duration
FROM your_table;
TIMEDIFF() function
MySQL TIMEDIFF()
returns the differences between two time or datetime expressions. It is to be noted that two expressions must be of same type.
Syntax :
TIMEDIFF(expr1,expr2)
Arguments
Name Description
expr1 A datetime value.
expr2 A datetime value.
EDIT:
If you want to get the duration in words (e.g. x hours y minutes z seconds
):
SELECT
CONCAT
(
IF(HOUR(TIMEDIFF(end_time,start_time)) > 0, CONCAT(HOUR(TIMEDIFF(end_time,start_time)), ' hours'),''),
IF(MINUTE(TIMEDIFF(end_time,start_time)) > 0 , CONCAT(MINUTE(TIMEDIFF(end_time,start_time)),' minutes'),''),
IF(SECOND(TIMEDIFF(end_time,start_time)) > 0 , CONCAT(SECOND(TIMEDIFF(end_time,start_time)),' seconds'),'')
) AS duration
FROM your_table
Demonstration:
SET @end_time := '20:50:00';
SET @start_time := '18:40:00';
SELECT
CONCAT(
IF(HOUR(TIMEDIFF(@end_time,@start_time)) > 0, CONCAT(HOUR(TIMEDIFF(@end_time,@start_time)), ' hours '),''),
IF(MINUTE(TIMEDIFF(@end_time,@start_time)) > 0 , CONCAT(MINUTE(TIMEDIFF(@end_time,@start_time)),' minutes '),''),
IF(SECOND(TIMEDIFF(@end_time,@start_time)) > 0 , CONCAT(SECOND(TIMEDIFF(@end_time,@start_time)),' seconds'),'')
) AS duration;
output: 2 hours 10 minutes