Search code examples
cakephpdate-comparisoncakephp-3.2

CakePHP 3 : date comparison in view


I'm working on CakePHP 3.2.

I want to compare date from timestamp in database with isThisMonth() function of CakePHP.

I am listing products whose created date is within 1 month. It will show NEW badge with product.

This is what I have done in view

<?php $date = new DateTime($product->created);
      $date = $date->format('Y-m-d');
      if ($date->isThisMonth()): ?>   // error is pointing this line
         <span class="new-product"> NEW</span>
<?php endif; ?>

Here $product is an error item and created is a timestamp column in database.

But this gives error as

Call to a member function isThisMonth() on string

Solution

  • Try adding this below $date = $date->format('Y-m-d');

    $time = new Time($date);
    

    then swap $date->isThisMonth()): with $time->isThisMonth()):

    http://book.cakephp.org/3.0/en/core-libraries/time.html#comparing-with-the-present

    include use Cake\I18n\Time; in view.ctp.