Alex Rivera | Logout

Are PHP DateInterval comparable like DateTime?

Asked 2012-03-03T16:50:25.757
31

I discovered that a DateTime object in PHP can be compared to another as the ">" and "<" operators are overloaded.

Is it the same with DateInterval?

As I was trying to answer this question, I found something strange:

<?php 

$today = new DateTime();
$release  = new DateTime('14-02-2012');
$building_time = new DateInterval('P15D');
var_dump($today->diff($release));
var_dump($building_time);
var_dump($today->diff($release)>$building_time);
var_dump($today->diff($release)<$building_time);
if($today->diff($release) < $building_time){
    echo 'oK';
}else{
    echo 'Just a test';
}

It always echoes "Just a test". The var_dump outputs are:

object(DateInterval)#4 (8) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(18)
  ["h"]=>
  int(16)
  ["i"]=>
  int(49)
  ["s"]=>
  int(19)
  ["invert"]=>
  int(1)
  ["days"]=>
  int(18)
}
object(DateInterval)#3 (8) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(15)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
}
bool(false)
bool(true)

When I try with a DateTime as "01-03-2012" everything works.

Edit
Report

1 Answer

-3

I used the following workaround comparing DateIntervals:

version_compare(join('.', (array) $dateIntervalA), join('.', (array) $dateIntervalB));
answered 2012-08-07T21:17:01.950

Your Answer