Comparing Date with DateTime in Cake 5

Hi,

Recently migrated my app to Cake 5 - I’ve run into issues in my existing code when comparing two dates, where suddenly the result is always false. For example $date1 < $date2.

After some digging it seems like that cause of this new behaviour is I am comparing Cake\I18N\Date objects with Cake\I18N\DateTime objects. Previously I believe I was using FrozenDate\FrozenTime and the migrations script automatically replaced them.

In the cake5 documentation it says that Date objects have a fixed time of 00:00:00 - so one would think that you could compare these two objects simply?

I was wondering if I others are able to replicate this behaviour and, if so, is it the correct/desired behaviour in CakePHP 5? Perhaps I should avoid using comparison operators altogether and instead use the objects comparison methods?

Thanks!

I do agree that this is weird…

$yesterday = new \Cake\I18n\Date('yesterday');
$now = new \Cake\I18n\DateTime('now');

$this->assertTrue($yesterday->toNative() < $now->toNative());
$this->assertTrue($yesterday < $now);

the second assertion fails but the first works

1 Like

well… as always its a bit more complicated.

The reason why this this is not working anymore since CakePHP 5 (and more specifically since Chronos 3) is the fact, that Date objects and DateTime Objects don’t share the same DateTimeImmutable class anymore.

See Release Chronos 3.0.2 · cakephp/chronos · GitHub as well as Reasoning around no longer extending native DateTimeImmutable · Issue #410 · cakephp/chronos · GitHub

So your best course would be to call ->toNative() to both instances since then you will always get a DateTimeImmutable object.

1 Like

Okay, makes sense. Thanks! It may be worth spelling this out in the migration guide - it’s quite difficult to spot since it doesn’t throw any errors.

Well, it’s kind of mentioned in the docs as you can see here:
https://book.cakephp.org/5/en/appendices/5-0-migration-guide.html#database

Sure, it doesn’t exactly mention this specific problem but a special notice would definitely help.

1 Like