Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a time difference to an array with PHP?

Tags:

php

I have the following array structure in MySQL. There could be no items or many items; the example shows only three.

Array
(
    [0] => Array
        (
            [id] => 1
            ...
            [start_time] => 09:00:00
            [finish_time] => 10:20:00
            ...
        )

    [1] => Array
        (
            [id] => 2
            ...
            [start_time] => 13:00:00
            [finish_time] => 14:20:00
            ...
        )
    [2] => Array
        (
            [id] => 23
            ...
            [start_time] => 18:05:00
            [finish_time] => 19:35:00
            ...
        )

     etc etc

)

I want to add the time difference between start_time and finish_time and find out the total time with PHP.

For example, the above should produce 250min or 4 hr 10min (80 min + 80min + 90min). How do I do this?

like image 591
shin Avatar asked Feb 27 '26 19:02

shin


2 Answers

In PHP:

$total_diff = 0;

foreach($items as $item)
{
    $total_diff += strtotime($item['finish_time']) - strtotime($item['start_time']);
}

The strtotime() function will convert the time value to seconds. You can then convert the $total_diff value to minutes, hours, etc as required.

If you have access to modify the original MySQL query, you could do it in a single query:

SELECT sum( UNIX_TIMESTAMP(finish_time) - UNIX_TIMESTAMP(start_time) )
FROM table

In the above, UNIX_TIMESTAMP performs the same function as strtotime() in PHP.

like image 97
ConroyP Avatar answered Mar 01 '26 09:03

ConroyP


<?php

        $arr = array(  0 => Array
                (
                        'start_time' => '09:00:00',
                        'finish_time' => '10:20:00'
                ),

                1 => Array
                (

                        'start_time' => '13:00:00',
                        'finish_time' => '14:20:00'
                ),
                2 => Array
                (

                        'start_time' => '18:05:00',
                        'finish_time' => '19:35:00'


                )
        );
        $accumulator = 0;
        foreach($arr as $entry) {
            $accumulator += strtotime($entry['finish_time']) - strtotime($entry['start_time']);
        }
        $hours = floor($accumulator / 3600);
        $mins = ($accumulator-$hours*3600)/60;
        echo "$hours:$mins";
        ?>

this is my output:

4:10

like image 37
ITroubs Avatar answered Mar 01 '26 08:03

ITroubs