Search code examples
yii2yii2-basic-app

Yii2 count day between 2 dates in gridview


            'class' => 'kartik\grid\FormulaColumn', 
            'header' => 'Days Work', 
            'value' => function ($model, $key, $index, $widget) { 
                $time = new \DateTime('now');
                $today = $time->format('Y-m-d');
                $p = compact('model', 'key', 'index');
                $datetime2 = $model->activedate;
                $interval = $today->diff($datetime2)->days;
                return $interval;
            },
            'headerOptions' => ['class' => 'kartik-sheet-style'],
            'hAlign' => 'right', 
            'width' => '7%',
        ],

I used the code above to count the day between today's date and the active date. The code show the errors Call to a member function diff() on string.

Please tell me where I'm wrong.

Thank you.


Solution

  • you need to use the DateTime object to calculate diff instead of the $today variable, which is a string (hence the error message you're getting)

    replace:

    $interval = $today->diff($datetime2)->days;
    

    with

    $interval = $time->diff($datetime2)->days;