Search code examples
phpsonata

How to use is current year from carbon library on sonata


I am new at sonata and i am trying to use the carbon library to generate an output of all the records from this year.

This is from the carbon library Carbon::isCurrentYear no arguments returns bool Checks if the instance is in the same year as the current moment. Method added 1.22.0 no arguments

The following is the code i am trying to apply

 public function getIsActiveThisYear(): bool
    {
        $now = Carbon::isCurrentYear();
        $endofyear = $endDate->year;
        $startofyear = $startDate->year;
        return $this->$endofyear == $now || $this->$startofyear == $now;  
    }

The error as a result of this code is:

isCurrentYear does not exist

Solution

  • Just do this:

    $date = new DateTime(); // Carbon extends the PHP DateTime class so it's the same.
    $thisYear = $date->format('Y');
    

    Check the docs! :-)

    https://www.php.net/manual/en/class.datetime.php

    You will also need to pass your start and end dates

    public function getIsActiveThisYear(DateTime $startDate, DateTime $endDate): bool