0

I need to subtract data time 2 times to get the final time, i got this "05:00"-"01:00"-"00:30".

$time1 = new dateTime('05:00'); $time2 = new dateTime('01:00'); $time3 = new dateTime('00:30'); $result = $time1->diff($time2);

and using this I could pull the difference from $time1 and $time2 but then i can't use ->diff again because it's dateInterval now.

Embek
  • 27
  • 1
  • 2
  • 11
  • Use public DateInterval::format ( string $format ) : string – Osama Apr 23 '20 at 07:51
  • Does this answer your question? [finding out difference between two times](https://stackoverflow.com/questions/5177334/finding-out-difference-between-two-times) – dmuensterer Apr 23 '20 at 07:52

3 Answers3

1

A possible solution to this can be using DateInterval instances directly with the DateTime::sub() method.

$time1 = new DateTime();
$time2 = new DateInterval('PT5H');
$time3 = new DateInterval('PT30M');

$result = $time1
    ->sub($time2)
    ->sub($time3)
    ->format('Y-m-d H:i:s');

var_dump($result); // 2020-04-23 04:24:24 (5 hours and 30 minutes earlier)
Marcel
  • 4,854
  • 1
  • 14
  • 24
0

As specified in the DateTime::diff docs, it is defined as

DateTime::diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval and therefore returns of type DateInterval.

There are already other correct answers to achieve the subtraction in PHP:

finding out difference between two times

dmuensterer
  • 1,875
  • 11
  • 26
  • As written above the questioner already knows how to find out the difference between two dates. His issue is how to subtract more than one time from another. So this answer is not helping. – Marcel Apr 23 '20 at 07:57
0

How about this?

$time1 = '05:00';
$time2 = '01:00';
$time3 = '00:30';

function str_to_minutes($str) {
    $arr = explode(':', $str);
    return (int)$arr[0] * 60 + (int)$arr[1];
}

function minutes_to_str($min) {
    echo sprintf("%02d:%02d", $min / 60, $min % 60);
}
echo minutes_to_str(str_to_minutes($time1) - str_to_minutes($time2) - str_to_minutes($time3));
//03:30
Star_Man
  • 1,091
  • 1
  • 13
  • 30