Björn C
Björn C

Reputation: 4008

DateTime "diff"

I think Time object is just a mess. I really never learn how they works.
I have an array with data: 09:00-09:20 and 12:30-13:00.
Now i like to calculate the time between 09:00-09:20.
So i break up the array:

$break_1_dur = $usr_breaks['skift_rast1'];
//returns: 09:00-09:20

I break up the string:

$break_1_start = substr($break_1_dur,0,5);
//returns: 09:00                   

$break_1_ends = substr($break_1_dur,6,5);
//returns: 09:20

And now i'll use DateTime diff to calculate the time:

$break_1_dur = $break_1_start->diff($break_1_ends);

I have tried to make strings to "DateTime" with:

$break_1_start = new DateTime();

How can i in a easy way calculate this?

Upvotes: 1

Views: 99

Answers (1)

Rizier123
Rizier123

Reputation: 59681

This should work for you:

Here I first split your array into the following structure with array_map():

Array
(
    [skift_rast1] => Array
        (
            [start] => 09:00
            [end] => 09:20
        )

    [skift_rast2] => Array
        (
            [start] => 12:30
            [end] => 13:00
        )

)

The I loop through all $times and calculate the difference with creating DateTime objects and get the difference via diff():

<?php

    $usr_breaks = ["skift_rast1" => "09:00-09:20", "skift_rast2" => "12:30-13:00"];
    $times = array_map(function($v){
        return array_combine(["start", "end"], explode("-", $v));
    }, $usr_breaks);


    //print differences
    foreach($times as $time) {
        $timeOne = new DateTime($time["start"]);
        $timeTwo = new DateTime($time["end"]);
        $interval = $timeOne->diff($timeTwo);
        echo sprintf("%d hours %d minutes<br>", $interval->h , $interval->i);
    }

?>

output:

0 hours 20 minutes
0 hours 30 minutes

Upvotes: 3

Related Questions