-1

I have two intervals:

$intervalFrom = DateInterval('12:00')
$intervalTo = DateInterval('1:30')

Output must be:

DateInterval('10:30')

I try

$newInterval =  $intervalFrom->sub($intervalTo);

But It not work

Chathuranga Chandrasekara
  • 20,548
  • 30
  • 97
  • 138
  • you do not subtract `DateInterval` from `DateInterval`, you subtract `DateInterval` from `DateTime`. Now, if you elaborate on what you need this for, we might actually help you. – Kevin Kopf Mar 29 '18 at 08:22
  • Add [error reporting](http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php/845025#845025) to the top of your file(s) _while testing_ right after your opening PHP tag for example ` – RiggsFolly Mar 29 '18 at 08:30
  • There is no `DateInterval->sub()` method – RiggsFolly Mar 29 '18 at 08:41

1 Answers1

0

You could create 2 times a DateInterval using PT12H and PT1H30M.

To get a difference, you could use the DateTime diff method.

Create 2 datetimes and pass 2 fixed starting points like "midnight" and for both of them add an interval.

Retrieve the number of hours h and minutes i and use those to create a new DateInterval:

$intervalFrom = new DateInterval('PT12H');
$intervalTo = new DateInterval('PT1H30M');
$d1 = new DateTime("midnight");
$d1->add($intervalFrom);
$d2 = new DateTime("midnight");
$d2->add($intervalTo);
$diff = $d1->diff($d2);
$strResult = sprintf("PT%sH%sM", $diff->h, $diff->i);
$resultDateInterval = new DateInterval($strResult);

Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70