Quantcast
Channel: Issues for Drupal core
Viewing all articles
Browse latest Browse all 301499

Ability to diff between two DrupalDateTime objects

$
0
0

Calling DrupalDateTime->diff() method doesn't work if you pass in another DrupalDateTime as it's first argument - it will always return false;

for example:

$a = \Drupal\Core\Datetime\DrupalDateTime::createFromFormat('Y-m-d', '2013-01-01');
$b = \Drupal\Core\Datetime\DrupalDateTime::createFromFormat('Y-m-d', '2013-01-11');
$diff = $a->diff($b);
//$diff = false

Expected $diff to be a DateInterval similarly to if we had called it with a DateTime object, instead it is false.

As a work-around, you have to do something like this:

$a = \Drupal\Core\Datetime\DrupalDateTime::createFromFormat('Y-m-d', '2013-01-01');
$b = \Drupal\Core\Datetime\DrupalDateTime::createFromFormat('Y-m-d', '2013-01-11');
$b2 = DateTime::createFromFormat('U', $b->format('U'));
$diff = $a->diff( $b2 );
//$diff = a DateInterval object

After a closer look it seems that DrupalDateTime inherits from DateTimePlus which is a sort of wrapper for DateTime

DateTimePlus passes all method calls which it doesn't implement on to the internal PHP DateTime class (if that method exists in PHP DateTime class)

(as an aside, why doesn't DateTimePlus extend DateTime?)

This doesn't work as expected with the diff method though because diff needs a DateTime object.

I'm not sure how to solve it..

Would it be ok to for DateTimePlus or DrupalDateTime to implement it's own diff method?

Or perhaps just allow access to the protected dateTimeObject so it can be passed in to the diff function without having to instantiate a new DrupalDateTime object?


Viewing all articles
Browse latest Browse all 301499

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>