<p>What is the best way to count the time between two datetime values fetched from MySQL when I need to count only the time between hours 08:00:00-16:00:00.</p>

<p>For example if I have values 2008-10-13 18:00:00 and 2008-10-14 10:00:00 the time difference should be 02:00:00.</p>

<p>Can I do it with SQL or what is the best way to do it? I'm building a website and using PHP.</p>

<p>Thank you for your answers.</p>

<p>EDIT: The exact thing is that I'm trying to count the time a "ticket" has been in a specific state during working hours. The time could be like a couple weeks.</p>

<p>EDIT2: I have no problems counting the actual time difference, but substracting that off-time, 00:00:00-08:00:00 and 16:00:00-00:00:00 per day.</p>

<p>-Samuli</p>

The
TIMEDIFF
function
TIMEDIFF() returns expr1 – expr2
  expressed as a time value. expr1 and
  expr2 are time or date-and-time
  expressions, but both must be of the
  same type.
```
```
mysql> SELECT TIMEDIFF('2000:01:01 00:00:00',
    ->                 '2000:01:01 00:00:00.000001');
        -> '-00:00:00.000001'
mysql> SELECT TIMEDIFF('2008-12-31 23:59:59.000001',
    ->                 '2008-12-30 01:01:01.000002');
        -> '46:58:57.999999'
```
```