0

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.

1000111
  • 13,169
  • 2
  • 28
  • 37
Harendra Singh
  • 203
  • 4
  • 13
  • 1
    Possible duplicate of [Calculate difference between two datetimes in MySQL](http://stackoverflow.com/questions/10907750/calculate-difference-between-two-datetimes-in-mysql) – G07cha Aug 31 '16 at 05:57

1 Answers1

2

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

1000111
  • 13,169
  • 2
  • 28
  • 37